From 71eed4e5374e2cd8448a82fc0f746c909cd508d8 Mon Sep 17 00:00:00 2001 From: tgyuu-An Date: Sat, 18 May 2024 02:01:11 +0900 Subject: [PATCH] 2024-05-18 --- tgyuuAn/README.md | 1 + ...44\355\212\270\354\233\214\355\201\254.py" | 40 +++++++++++++++++++ 2 files changed, 41 insertions(+) create mode 100644 "tgyuuAn/\354\234\240\353\213\210\354\230\250 \355\214\214\354\235\270\353\223\234/\354\271\234\352\265\254 \353\204\244\355\212\270\354\233\214\355\201\254.py" diff --git a/tgyuuAn/README.md b/tgyuuAn/README.md index cbc8e16b..875c8b39 100644 --- a/tgyuuAn/README.md +++ b/tgyuuAn/README.md @@ -55,4 +55,5 @@ | 51차시 | 2023.04.07 | BFS | 과외맨 | https://github.com/AlgoLeadMe/AlgoLeadMe-1/pull/179 | 52차시 | 2023.05.06 | 위상정렬 | 게임 개발 | https://github.com/AlgoLeadMe/AlgoLeadMe-1/pull/182 | 53차시 | 2023.05.09 | 백트래킹 | 2048 (Easy) | https://github.com/AlgoLeadMe/AlgoLeadMe-1/pull/184 +| 55차시 | 2023.05.18 | 유니온 파인드 | 친구 네트워크 | https://github.com/AlgoLeadMe/AlgoLeadMe-1/pull/189 --- diff --git "a/tgyuuAn/\354\234\240\353\213\210\354\230\250 \355\214\214\354\235\270\353\223\234/\354\271\234\352\265\254 \353\204\244\355\212\270\354\233\214\355\201\254.py" "b/tgyuuAn/\354\234\240\353\213\210\354\230\250 \355\214\214\354\235\270\353\223\234/\354\271\234\352\265\254 \353\204\244\355\212\270\354\233\214\355\201\254.py" new file mode 100644 index 00000000..4d44b637 --- /dev/null +++ "b/tgyuuAn/\354\234\240\353\213\210\354\230\250 \355\214\214\354\235\270\353\223\234/\354\271\234\352\265\254 \353\204\244\355\212\270\354\233\214\355\201\254.py" @@ -0,0 +1,40 @@ +import sys +from collections import defaultdict + +def input(): return sys.stdin.readline().rstrip() + +def find_parent(element, graph): + if graph[element] == element: return element + + parent = graph[element] + graph[element] = find_parent(parent, graph) + return graph[element] + +def union(first, second, graph, count): + x = find_parent(first, graph) + y = find_parent(second, graph) + + if x == y: return + + x, y = min(x, y), max(x, y) + graph[y] = x + count[x] += count[y] + count[y] = 0 + return + +T = int(input()) + +for _ in range(T): + F = int(input()) + index = 1 + parent = defaultdict(str) + count = defaultdict(lambda : 1) + + for _ in range(F): + first, second = input().split() + if parent[first] == "": parent[first] = first + if parent[second] == "": parent[second] = second + if parent[first] != parent[second]: union(first, second, parent, count) + + print(count[find_parent(first, parent)]) + \ No newline at end of file