Home BOJ. Friend Network (4195)
Post
Cancel

BOJ. Friend Network (4195)

[Link] https://www.acmicpc.net/problem/4195


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
import java.util.*;
import java.io.*;

public class Main {
	static BufferedReader br;
	public static void main(String[] args) throws IOException {
		br = new BufferedReader(new InputStreamReader(System.in));
		StringBuilder sb = new StringBuilder();
		String[] line;
		int t = toi(br.readLine());
		HashMap<String, Node> hm = new HashMap<>();

		for(int iter = 0; iter < t; iter++) {
			hm.clear();
			int f = toi(br.readLine());
			for(int i = 0; i < f; i++) {
				line = getLine();
				if(!hm.containsKey(line[0])) hm.put(line[0], new Node(line[0], 1));
				if(!hm.containsKey(line[1])) hm.put(line[1], new Node(line[1], 1));
				Node parentNode0 = getParent(hm, line[0]);
				Node parentNode1 = getParent(hm, line[1]);
				if(parentNode0.parent.compareTo(parentNode1.parent) < 0) {
					parentNode0.num += parentNode1.num;
					parentNode1.parent = parentNode0.parent;
					sb.append(parentNode0.num).append("\n");
				} else if(parentNode0.parent.equals(parentNode1.parent)){
					sb.append(parentNode0.num).append("\n");
				} else {
					parentNode1.num += parentNode0.num;
					parentNode0.parent = parentNode1.parent;
					sb.append(parentNode1.num).append("\n");
				}
			}
		}
		print(sb);
	}

	static Node getParent(HashMap<String, Node> hm, String s) {
		if(hm.get(s).parent.equals(s)) return hm.get(s);
		Node node = getParent(hm, hm.get(s).parent);
		hm.get(s).parent = node.parent;
		return node;
	}

	static class Node {
		String parent;
		int num;
		Node(String parent, int num) { this.parent = parent; this.num = num; }
	}

	static int toi(String s) { return Integer.parseInt(s); }
	static String[] getLine() throws IOException { return br.readLine().split(" "); }
	static <T> void print(T s) { System.out.print(s); }
	static <T> void println(T s) { System.out.println(s); }
}
This post is licensed under CC BY 4.0 by the author.