-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBJAlgo_4195.java
More file actions
57 lines (46 loc) · 1.7 KB
/
Copy pathBJAlgo_4195.java
File metadata and controls
57 lines (46 loc) · 1.7 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
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
public class BJAlgo_4195 {
static Map<String, String> parent = new HashMap<>();
static Map<String, Integer> networks = new HashMap<>();
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int testCase = Integer.parseInt(br.readLine());
for (int i = 0; i < testCase; i++) {
parent.clear();
networks.clear();
int f = Integer.parseInt(br.readLine());
for (int j = 0; j < f; j++) {
String[] people = br.readLine().split(" ");
if (!parent.containsKey(people[0])) {
parent.put(people[0], people[0]);
networks.put(people[0], 1);
}
if (!parent.containsKey(people[1])) {
parent.put(people[1], people[1]);
networks.put(people[1], 1);
}
union(people[0], people[1]);
System.out.println(networks.get(find(people[0])));
}
}
}
private static String find(String p) {
if (p.equals(parent.get(p))) {
return p;
}
String par = find(parent.get(p));
parent.put(p, par);
return parent.get(p);
}
private static void union(String a, String b) {
String parent1 = find(a);
String parent2 = find(b);
if (!parent1.equals(parent2)) {
parent.put(parent2, parent1);
networks.put(parent1, networks.get(parent1) + networks.get(parent2));
}
}
}