There are n courses numbered 0 … n−1 and m prerequisite pairs. The pair a b means course b must be taken before course a. Can every course be finished?
Input
- Line 1:
n m (1 ≤ n ≤ 10^5, 0 ≤ m ≤ 2·10^5)
- Next m lines:
a b
Output
YES if all courses can be finished, otherwise NO.
Hint
This is cycle detection on a directed graph. Kahn's algorithm: repeatedly take a course with no remaining prerequisites; if you run out before visiting all n, a cycle exists.
Read from standard input and write to standard output. 5 test cases in total (3 hidden). Tests for this language run inside your browser.