From 4d9634c98a8eaa6723adbce478039e2f6dc6acaf Mon Sep 17 00:00:00 2001 From: Donew <47556347+03do-new30@users.noreply.github.com> Date: Thu, 27 Mar 2025 23:29:13 +0900 Subject: [PATCH] =?UTF-8?q?[20250327]=20BOJ=20/=20G2=20/=20=EC=B9=9C?= =?UTF-8?q?=EA=B5=AC=20=EB=84=A4=ED=8A=B8=EC=9B=8C=ED=81=AC=20/=20?= =?UTF-8?q?=EC=8B=A0=EB=8F=99=EC=9C=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...44\355\212\270\354\233\214\355\201\254.md" | 80 +++++++++++++++++++ 1 file changed, 80 insertions(+) create mode 100644 "03do-new30/202503/27 BOJ G2 \354\271\234\352\265\254 \353\204\244\355\212\270\354\233\214\355\201\254.md" diff --git "a/03do-new30/202503/27 BOJ G2 \354\271\234\352\265\254 \353\204\244\355\212\270\354\233\214\355\201\254.md" "b/03do-new30/202503/27 BOJ G2 \354\271\234\352\265\254 \353\204\244\355\212\270\354\233\214\355\201\254.md" new file mode 100644 index 00000000..a364c6eb --- /dev/null +++ "b/03do-new30/202503/27 BOJ G2 \354\271\234\352\265\254 \353\204\244\355\212\270\354\233\214\355\201\254.md" @@ -0,0 +1,80 @@ +```java +import java.io.*; +import java.util.*; + +public class Main { + + static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + static int F, cnt; + static Map map; + static int[] parents, friends; + + public static void main(String[] args) throws IOException { + int T = Integer.parseInt(br.readLine()); + for (int tc = 1; tc <= T; tc++) { + + F = Integer.parseInt(br.readLine()); + map = new HashMap<>(); + cnt = 0; + + makeSet(); + init(); + + for (int i = 0 ; i < F; i++) { + StringTokenizer st = new StringTokenizer(br.readLine()); + String name1 = st.nextToken(); + String name2 = st.nextToken(); + addName(name1); // 이름 관리 + addName(name2); + union(map.get(name1), map.get(name2)); + // 두 사람의 친구 네트워크에 몇 명이 있는지 구한다. + int root = find(map.get(name1)); + System.out.println(friends[root]); + } + } + br.close(); + } + + static void addName(String name) { + if (map.containsKey(name)) return; + map.put(name, cnt++); + } + + static void init() { + // friends[i] = i가 집합의 대표자일 때, 해당 집합에 속하는 친구들의 수 + friends = new int[F*2]; + for (int i = 0; i < F*2; i++) { + friends[i] = 1; // 초기에는 자기 자신만 친구... + } + } + + static void makeSet() { + parents = new int[F * 2]; // F개 관계 -> 최대 F*2명의 사람 존재 가능 + for (int i = 0; i < F * 2; i++) { + parents[i] = i; + } + } + + static int find(int a) { + if (a == parents[a]) return a; + return parents[a] = find(parents[a]); + } + + static boolean union(int a, int b) { + int aRoot = find(a); + int bRoot = find(b); + if (aRoot == bRoot) return false; + if (aRoot < bRoot) { + parents[bRoot] = aRoot; + friends[aRoot] += friends[bRoot]; // 친구 수 합치깅 + } else { + parents[aRoot] = bRoot; + friends[bRoot] += friends[aRoot]; // 친구 수 합치깅 + } + return true; + } + + +} + +```