Popular Cows
InterviewTime limit1sMemory limit1024 MB
Given M directed pairs (A, B) meaning cow A thinks cow B is popular, count the cows that every other cow can reach through transitive popularity.
- Level
Medium5 of 10
- Topics
- Graph, DFS, Topological sort
- Solved
- No attempts yet
Problem
Every cow's dream is to become the most popular cow in the herd. In a herd of () cows, you are given up to () ordered pairs of the form . Each pair says that cow thinks cow is popular. Popularity is transitive: if thinks is popular and thinks is popular, then also thinks is popular, even if no pair in the input says so. Compute the number of cows that every other cow considers popular.
Input
The first line contains two space-separated integers and . Each of the next lines contains two space-separated integers and , meaning that cow thinks cow is popular.
Output
Print a single integer: the number of cows that are considered popular by every other cow.
Hint
Cow 3 is the only cow with high popularity.