forked from mbobesic/algorithms-playground
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProvingEquivalences.java
142 lines (108 loc) · 2.47 KB
/
ProvingEquivalences.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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
// link: https://open.kattis.com/problems/equivalences
// name: Proving Equivalences
package kattis;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.Scanner;
public class ProvingEquivalences {
private static Scanner input;
private static int cnt, scnt;
private static int[] id, pre, low;
private static Deque<Integer> stack;
private static ArrayList<ArrayList<Integer>> graph;
public static void main(String[] args) {
input = new Scanner(System.in);
int testsLeft = input.nextInt();
while (testsLeft-- > 0) {
solve();
}
input.close();
}
private static void solve() {
cnt = 0;
scnt = 0;
int vertexCount = input.nextInt();
int edgeCount = input.nextInt();
graph = new ArrayList<>();
for (int i = 0; i < vertexCount + 1; ++i) {
ArrayList<Integer> neighbours = new ArrayList<>();
graph.add(neighbours);
}
for (int i = 0; i < edgeCount; ++i) {
int from = input.nextInt();
int to = input.nextInt();
graph.get(from).add(to);
}
stack = new ArrayDeque<>();
id = new int[vertexCount + 1];
pre = new int[vertexCount + 1];
low = new int[vertexCount + 1];
for (int i = 0; i < vertexCount + 1; ++i) {
id[i] = -1;
pre[i] = -1;
low[i] = -1;
}
for (int v = vertexCount; v > 0; --v) {
if (pre[v] == -1)
strong_components(v);
}
int[] outDegrees = new int[scnt];
int[] inDegrees = new int[scnt];
for (int from = 0; from < vertexCount + 1; ++from) {
for (Integer to : graph.get(from)) {
if (id[from] == id[to]) {
continue;
}
++outDegrees[id[from]];
++inDegrees[id[to]];
}
}
if (scnt == 1){
System.out.println(0);
return;
}
int sinks = 0;
int sources = 0;
for (int v = scnt - 1; v >= 0; --v) {
if (outDegrees[v] == 0){
++sinks;
}
if (inDegrees[v] == 0){
++sources;
}
}
int result = sinks > sources ? sinks : sources;
System.out.println(result);
}
private static void strong_components(int w) {
int t;
int min = cnt;
low[w] = cnt;
pre[w] = cnt;
++cnt;
stack.push(w);
ArrayList<Integer> neighbours = graph.get(w);
for (Integer neighbour : neighbours) {
if (pre[neighbour] == -1) {
strong_components(neighbour);
}
if (low[neighbour] < min) {
min = low[neighbour];
}
}
if (min < low[w]) {
low[w] = min;
return;
}
while (true) {
t = stack.pop();
id[t] = scnt;
low[t] = graph.size();
if (t == w) {
break;
}
}
scnt++;
}
}