All problems

Problem 168

Course Schedule

Medium · 20 pts · Graph, Topological Sort, Depth-First Search

Problem

There are N courses labelled 1 to N and M prerequisite pairs. A pair "a b" means course b must be completed before course a. Decide whether it is possible to finish all the courses. Model the courses as a directed graph with an edge b → a for every pair. All courses can be finished exactly when this graph has no cycle, for example when 1 requires 2 and 2 requires 1. Kahn's algorithm (repeatedly removing courses with no unfinished prerequisites) or a DFS cycle check answers this.

Input

First line: integers N and M. Next M lines: a pair a b.

Output

Print YES or NO.

Constraints

1 <= N <= 2000; 0 <= M <= 5000

Example input

2 1
2 1

Example output

YES

Explanation

There are 2 courses and one pair "2 1": course 1 must be taken before course 2. Take course 1 and then course 2, and both are finished, so the answer is YES.

Every problem here can be used in a RelayTrixCode team match. Create a room.

Previous: Smallest Topological Order Next: Minimum Spanning Tree