15006 - Course Scheduling   

Description

In the Department of Computer Science at a university, students must complete a series of required courses to successfully earn their degree. However, there are often "prerequisite" rules between courses. For example, you must complete "Programming" before you can take "Data Structures".

We can view these courses and prerequisite rules as a Directed Graph. Each vertex in the graph represents a course, and each directed edge U -> V indicates that course U is a prerequisite for course V (you must complete U before taking V).

As a teaching assistant in the department, you need to write a C/C++ program. Given the prerequisite relationship graph of all courses, please calculate a valid course-taking sequence. In graph theory, this valid linear sequence is known as a Topological Order (or Topological Sort).

Pay attention to two important rules:

  1. Deadlock Detection: If there is a directed cycle in the prerequisite relationships, it means students will fall into a deadlock (e.g., course A is a prerequisite for B, and B is a prerequisite for A) and can never complete all courses. In this case, directly output -1.
  2. Unique Solution Rule: Since there might be more than one valid course-taking sequence, to standardize the answers for the judging system, whenever you select the next course to take, always prioritize the course with the smallest course ID. (i.e., output the lexicographically smallest topological order).

Your program MAY use C/C++ standard library headers.

Input

The first line contains two integers N and M (1 <= N <= 1,000, 0 <= M <= 5,000), representing the total number of courses and the number of prerequisite relationships (directed edges), respectively. Courses are numbered from 0 to N-1.

The next M lines each contain two integers U and V (0 <= U, V < N and U != V), representing a directed edge from U to V. This means course U must be completed before course V can be taken.

(Note: The input test cases may contain duplicate prerequisite relationships, which should simply be treated as a single restriction when processing. The graph may also contain isolated courses that have no prerequisites or dependent courses.)

Output

If all courses can be successfully completed, output a single line containing N integers representing the valid topological order. Output format requirements: Adjacent numbers must be separated by a single space character. There must be NO trailing space after the last number.

If a directed cycle exists in the graph, making it impossible to complete all courses, output -1 on a single line.

Each line of output must be terminated by a newline character ('\n').

Sample Input  Download

Sample Output  Download

Tags

yan_ds



Discuss