THINK FIRST·CODE LATER

← All labs

Course plan: Kahn's topological sort

Problem

Courses are numbered 0 … n − 1. A line u v means "course u must be taken before course v" (a directed edge u → v). Print an order in which all courses can be taken.

Input

n m
u1 v1      // m directed edges
...

Rules

  • Use Kahn's algorithm (in-degrees). Whenever several courses are available (in-degree 0), always take the smallest number first — a PriorityQueue<Integer> does this.
  • If not every course can be placed (the prerequisites contain a cycle), print exactly cycle.

Output — the order on one line, separated by single spaces. For

7 8
5 2
5 0
4 0
4 1
2 3
3 1
6 2
6 4

the output is

5 6 2 3 4 0 1

Data for this lab

Your program reads its data from standard input. Download the file, then give it to your program as shown below. Start with data set 1: its expected output is given.

d15-2-data-1.txt

7 8
5 2
5 0
4 0
4 1
2 3
3 1
6 2
6 4
What your program must print for d15-2-data-1.txt
5 6 2 3 4 0 1

Run your program first, then open this and compare line by line: your output must contain these lines exactly.

How to give the file to my program

Terminal (macOS, Linux, or Windows Command Prompt), after compiling:

java Main < d15-2-data-1.txt

Windows PowerShell does not understand <:

Get-Content d15-2-data-1.txt | java Main

IntelliJ IDEA: Run → Edit Configurations → Redirect input from. Or simply paste the content of the file into the console when the program waits for input.

Write it here or in your IDE, then paste it. Compile and test it yourself before comparing. Your code stays in your browser — it is never sent to or stored on the server.