File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ ``` java
2+ import java.io.* ;
3+ import java.util.* ;
4+
5+ public class Main {
6+ static int [] parent;
7+ static int [] count;
8+
9+ public static void main (String [] args ) throws IOException {
10+ BufferedReader br = new BufferedReader (new InputStreamReader (System . in));
11+ int T = Integer . parseInt(br. readLine());
12+
13+ StringBuilder sb = new StringBuilder ();
14+ while (T -- > 0 ) {
15+ int F = Integer . parseInt(br. readLine());
16+
17+ parent = new int [F * 2 ];
18+ count = new int [F * 2 ];
19+ for (int i = 0 ; i < F * 2 ; i++ ) {
20+ parent[i] = i;
21+ count[i] = 1 ;
22+ }
23+
24+ Map<String , Integer > map = new HashMap<> ();
25+ int id = 0 ;
26+
27+ for (int i = 0 ; i < F ; i++ ) {
28+ StringTokenizer st = new StringTokenizer (br. readLine());
29+ String f1 = st. nextToken();
30+ String f2 = st. nextToken();
31+
32+ if (! map. containsKey(f1)) map. put(f1, id++ );
33+ if (! map. containsKey(f2)) map. put(f2, id++ );
34+
35+ sb. append(union(map. get(f1), map. get(f2))). append(" \n " );
36+ }
37+ }
38+ System . out. print(sb. toString());
39+ }
40+
41+ static int find (int x ) {
42+ if (parent[x] == x) return x;
43+ return parent[x] = find(parent[x]);
44+ }
45+
46+ static int union (int x , int y ) {
47+ x = find(x);
48+ y = find(y);
49+
50+ if (x != y) {
51+ parent[y] = x;
52+ count[x] += count[y];
53+ }
54+
55+ return count[x];
56+ }
57+ }
58+ ```
You can’t perform that action at this time.
0 commit comments