-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathTopologicalSort.java
47 lines (47 loc) · 1.22 KB
/
TopologicalSort.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
package graph;
/**
* @verified
* - http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=GRL_4_B
*/
class TopologicalSort {
private final int n;
private final int[] ord;
private final int[] inv;
private final boolean isDAG;
public TopologicalSort(Digraph<? extends AbstractEdge> g) {
this.n = g.getV();
this.ord = new int[n];
this.inv = new int[n];
this.isDAG = build(g);
}
public boolean isDAG() {
return isDAG;
}
public int[] topologicalOrder() {
return isDAG ? ord : null;
}
public int[] topologicalOrderInv() {
return isDAG ? inv : null;
}
private boolean build(Digraph<? extends AbstractEdge> g) {
for (AbstractEdge e : g.getEdges()) {
inv[e.to]++;
}
int hd = 0, tl = 0;
for (int u = 0; u < n; u++) {
if (inv[u] == 0) {
ord[inv[u] = tl++] = u;
}
}
while (tl > hd) {
int u = ord[hd++];
for (AbstractEdge e : g.getEdges(u)) {
int v = e.to;
if (--inv[v] == 0) {
ord[inv[v] = tl++] = v;
}
}
}
return tl == n;
}
}