-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathSccTarjan.java
105 lines (90 loc) · 2.63 KB
/
SccTarjan.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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
/*
* Tarjan's algorithm to find the strongly connected components (SCC) of a graph using depth-first search (DFS)
*
* Time complexity: O(V + E)
*/
package codebook.graph;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Stack;
import java.util.StringTokenizer;
public class SccTarjan {
static BufferedReader br;
static PrintWriter out;
static StringTokenizer st;
static int n, m, cnt, idCnt;
static int[] disc, lo, id;
static boolean[] inStack;
static Stack<Integer> s = new Stack<Integer>();
static ArrayList<ArrayList<Integer>> adj = new ArrayList<ArrayList<Integer>>();
public static void main (String[] args) throws IOException {
br = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(new OutputStreamWriter(System.out));
// br = new BufferedReader(new FileReader("in.txt"));
// out = new PrintWriter(new FileWriter("out.txt"));
n = readInt();
m = readInt();
disc = new int[n];
lo = new int[n];
id = new int[n];
inStack = new boolean[n];
for (int i = 0; i < n; i++)
adj.add(new ArrayList<Integer>());
for (int i = 0; i < m; i++) {
int a = readInt() - 1;
int b = readInt() - 1;
adj.get(a).add(b);
}
for (int i = 0; i < n; i++)
if (disc[i] == 0)
dfs(i);
for (int i = 0; i < n; i++)
out.printf("Vertex %d is in component %d\n", i + 1, id[i]);
out.close();
}
static void dfs (int i) {
disc[i] = lo[i] = ++cnt;
inStack[i] = true;
s.push(i);
for (int j : adj.get(i)) {
if (disc[j] == 0) {
dfs(j);
lo[i] = Math.min(lo[i], lo[j]);
} else if (inStack[j]) {
lo[i] = Math.min(lo[i], disc[j]);
}
}
if (disc[i] == lo[i]) {
while (s.peek() != i) {
inStack[s.peek()] = false;
id[s.pop()] = idCnt;
}
inStack[s.peek()] = false;
id[s.pop()] = idCnt++;
}
}
static String next () throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine().trim());
return st.nextToken();
}
static long readLong () throws IOException {
return Long.parseLong(next());
}
static int readInt () throws IOException {
return Integer.parseInt(next());
}
static double readDouble () throws IOException {
return Double.parseDouble(next());
}
static char readCharacter () throws IOException {
return next().charAt(0);
}
static String readLine () throws IOException {
return br.readLine().trim();
}
}