-
Notifications
You must be signed in to change notification settings - Fork 0
/
TopologicalSortingKahn.java
65 lines (57 loc) · 1.62 KB
/
TopologicalSortingKahn.java
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
59
60
61
62
63
64
65
/** https://www.spoj.com/problems/TOPOSORT/ #topological-sort */
import java.util.ArrayList;
import java.util.PriorityQueue;
import java.util.Scanner;
class TopologicalSortingKahn {
public static boolean toposorting(
ArrayList<ArrayList<Integer>> graph, int[] inDegree, ArrayList<Integer> resultArr) {
PriorityQueue<Integer> zeroInDegree = new PriorityQueue<>();
for (int i = 1; i < inDegree.length; i++) {
if (inDegree[i] == 0) {
zeroInDegree.add(i);
}
}
while (!zeroInDegree.isEmpty()) {
int node = zeroInDegree.poll();
resultArr.add(node);
for (int neighbour : graph.get(node)) {
inDegree[neighbour] -= 1;
if (inDegree[neighbour] == 0) {
zeroInDegree.add(neighbour);
}
}
}
boolean ret = true;
for (int degree : inDegree) {
if (degree != 0) {
ret = false;
break;
}
}
return ret;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int m = sc.nextInt();
int sz = n + 1;
ArrayList<ArrayList<Integer>> graph = new ArrayList<>();
for (int i = 0; i < sz; i++) {
graph.add(new ArrayList<Integer>());
}
int[] inDegree = new int[sz];
ArrayList<Integer> resultArr = new ArrayList<>();
int u, v;
for (int i = 0; i < m; i++) {
u = sc.nextInt();
v = sc.nextInt();
graph.get(u).add(v);
inDegree[v] += 1;
}
if (toposorting(graph, inDegree, resultArr)) {
resultArr.forEach(x -> System.out.print(x + " "));
} else {
System.out.println("Sandro fails.");
}
}
}