Problem 429
Minimum Semesters to Finish Courses
Medium · 20 pts · Graph, Topological Sort
Problem
There are N courses labelled 1 to N, and M prerequisite pairs 'u v' meaning course u must be completed in an earlier semester than course v. In each semester you may take any number of courses, as long as all their prerequisites were completed in earlier semesters. Find the minimum number of semesters needed to take all courses, or -1 if the prerequisites contain a cycle and it is impossible. Processing the courses level by level (Kahn's algorithm) gives the answer.
Input
First line: N and M. Next M lines: a prerequisite pair u v.
Output
Print the minimum number of semesters, or -1.
Constraints
1 <= N <= 5000; 0 <= M <= 5000
Example input
3 2 1 3 2 3
Example output
2
Explanation
With 3 courses and prerequisites 1→3 and 2→3, courses 1 and 2 can be taken together in semester 1 and course 3 in semester 2: 2 semesters.