-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTopSort.java
More file actions
58 lines (48 loc) · 1.53 KB
/
TopSort.java
File metadata and controls
58 lines (48 loc) · 1.53 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
import java.util.*;
import java.io.*;
public class TopSort {
public static void main(String[] args) throws IOException {
FastScanner in = new FastScanner(System.in);
PrintWriter out = new PrintWriter(System.out);
int n = in.nextInt();
int m = in.nextInt();
ArrayList<Integer>[] adj = new ArrayList[n + 1];
Arrays.setAll(adj, x -> new ArrayList<>());
for (int i = 0; i < m; i++) {
int u = in.nextInt();
int v = in.nextInt();
adj[u].add(v);
}
ArrayDeque<Integer> sorted = topSort(n, adj);
//detects if there is a cycle = impossible to top sort
if (sorted.size() != n) {
System.out.println("IMPOSSIBLE");
return;
}
for (int x : sorted) {
out.print(x + " ");
}
out.close();
}
static ArrayDeque<Integer> topSort(int n, ArrayList<Integer>[] adj) {
ArrayDeque<Integer> ret = new ArrayDeque<>();
ArrayDeque<Integer> queue = new ArrayDeque<>();
int[] deg = new int[n + 1];
for (int i = 1; i <= n; i++) {
for (int j : adj[i]) {
deg[j]++;
}
}
for (int i = 1; i <= n; i++) {
if (deg[i] == 0) queue.addLast(i);
}
while (!queue.isEmpty()) {
int cur = queue.pollFirst();
ret.addLast(cur);
for (int to : adj[cur]) {
if (--deg[to] == 0) queue.addLast(to);
}
}
return ret;
}
}