|
| 1 | +import java.io.*; |
| 2 | +import java.util.*; |
| 3 | + |
| 4 | +public class Main { |
| 5 | + |
| 6 | + public static Map<String, Integer> friendIndex; |
| 7 | + public static int[] parent; |
| 8 | + public static int[] count; |
| 9 | + |
| 10 | + public static void main(String[] args) throws IOException { |
| 11 | + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); |
| 12 | + int T = Integer.parseInt(br.readLine()); |
| 13 | + StringBuilder sb = new StringBuilder(); |
| 14 | + for(int t=0; t<T; t++) { |
| 15 | + int F = Integer.parseInt(br.readLine()); |
| 16 | + friendIndex = new HashMap<>(); |
| 17 | + count = new int[F*2]; |
| 18 | + parent = new int[F*2]; |
| 19 | + for(int i=1; i<F*2; i++) { |
| 20 | + parent[i] = i; |
| 21 | + } |
| 22 | + int num = 0; |
| 23 | + for(int i=0; i<F; i++) { |
| 24 | + StringTokenizer st = new StringTokenizer(br.readLine()); |
| 25 | + String friend1 = st.nextToken(); |
| 26 | + String friend2 = st.nextToken(); |
| 27 | + if(!friendIndex.containsKey(friend1)) { |
| 28 | + count[num] = 1; |
| 29 | + friendIndex.put(friend1, num++); |
| 30 | + } |
| 31 | + if(!friendIndex.containsKey(friend2)) { |
| 32 | + count[num] = 1; |
| 33 | + friendIndex.put(friend2, num++); |
| 34 | + } |
| 35 | + int x = find(friendIndex.get(friend1)); |
| 36 | + int y = find(friendIndex.get(friend2)); |
| 37 | + union(x, y); |
| 38 | + sb.append(count[x]).append('\n'); |
| 39 | + } |
| 40 | + } |
| 41 | + System.out.print(sb); |
| 42 | + } |
| 43 | + |
| 44 | + public static int find(int x) { |
| 45 | + if(parent[x] == x) { |
| 46 | + return x; |
| 47 | + } |
| 48 | + parent[x] = find(parent[x]); |
| 49 | + return parent[x]; |
| 50 | + } |
| 51 | + public static void union(int x, int y) { |
| 52 | + x = find(x); |
| 53 | + y = find(y); |
| 54 | + if(x == y) { |
| 55 | + return; |
| 56 | + } |
| 57 | + parent[y] = x; |
| 58 | + count[x] += count[y]; |
| 59 | + } |
| 60 | +} |
0 commit comments