-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathTarjanGeeks.java
More file actions
129 lines (105 loc) · 3.16 KB
/
Copy pathTarjanGeeks.java
File metadata and controls
129 lines (105 loc) · 3.16 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
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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
import java.util.Scanner;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
import static java.lang.Math.*;
public class Main {
private static Scanner input;
private static List<Integer>[] adj;
private static int scc, time;
private static boolean[] onStack;
private static int[] disc, low, contract;
private static Stack<Integer> stack;
public static void tarjan() {
time = 0;
scc = 0;
low = new int[adj.length];
disc = new int[adj.length];
onStack = new boolean[adj.length];
contract = new int[adj.length];
stack = new Stack<Integer>();
for(int i = 0; i < adj.length; i++) {
disc[i] = -1;
low[i] = -1;
onStack[i] = false;
contract[i] = -1;
}
for(int i = 0; i < adj.length; i++)
if (disc[i] == -1)
dfs(i);
}
private static void dfs(int u) {
stack.push(u);
onStack[u] = true;
disc[u] = low[u] = time++;
for(int i = 0; i < adj[u].size(); i++) {
int v = adj[u].get(i);
if (disc[v] == -1) {
dfs(v);
low[u] = min(low[u], low[v]);
} else if(onStack[v] == true) {
low[u] = min(low[u], disc[v]);
}
}
if(low[u] == disc[u]) {
while(true) {
int node = stack.pop();
contract[node] = scc;
if(node == u) break;
}
scc++;
}
}
@SuppressWarnings("unchecked")
public static void solve() {
int n = toIntExact(input.nextLong());
int m = toIntExact(input.nextLong());
adj = new ArrayList[toIntExact(n)];
for (int i = 0; i < n; i++) {
adj[i] = new ArrayList<Integer>();
}
for(int i = 0; i < m; i++) {
int s1 = toIntExact(input.nextLong());
int s2 = toIntExact(input.nextLong());
adj[--s1].add(--s2);
}
tarjan();
boolean[] out = new boolean[scc];
boolean[] in = new boolean[scc];
for(int u = 0; u < adj.length; u++) {
for(int i = 0; i < adj[u].size(); i++) {
int v = adj[u].get(i);
if(contract[u] != contract[v]) {
out[contract[u]] = true;
in[contract[v]] = true;
}
}
}
int result1 = 0;
int result2 = 0;
for(int i = 0; i < scc; i++) {
if(!out[i]) {
result1++;
}
if(!in[i]) {
result2++;
}
}
if(scc == 1) {
System.out.println(0);
} else {
System.out.println(max(result1, result2));
}
}
public static void main(String[] arg) throws java.lang.Exception{
try {
input = new Scanner(System.in);
int x = toIntExact(input.nextLong());
for(int i = 0; i < x; i++) {
solve();
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}