Created
July 8, 2021 14:52
-
-
Save uchidama/790ec04fe1417ab8af0904c102bd98f1 to your computer and use it in GitHub Desktop.
AtCoder Beginner Contest 177 [ D - Friends ] https://atcoder.jp/contests/abc177/tasks/abc177_d
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
''' | |
[問題] | |
https://atcoder.jp/contests/abc177/tasks/abc177_d | |
[解説] | |
https://atcoder.jp/contests/abc177/editorial/90 | |
[参考] | |
AtCoder Beginner Contest 206(Sponsored by Panasonic) [ D - KAIBUNsyo ]をPythonでUnionFindを使って解く | |
https://uchidama.hatenablog.com/entry/2021/06/22/170804 | |
PythonでのUnion-Find(素集合データ構造)の実装と使い方 | |
https://note.nkmk.me/python-union-find/ | |
[結果] | |
PyPy3(7.3.0) AC 304ms | |
Python(3.8.2) AC 510ms | |
''' | |
import sys | |
from collections import defaultdict | |
class UnionFind(): | |
def __init__(self, n): | |
self.n = n | |
self.parents = [-1] * n | |
def find(self, x): | |
if self.parents[x] < 0: | |
return x | |
else: | |
self.parents[x] = self.find(self.parents[x]) | |
return self.parents[x] | |
def union(self, x, y): | |
x = self.find(x) | |
y = self.find(y) | |
if x == y: | |
return | |
if self.parents[x] > self.parents[y]: | |
x, y = y, x | |
self.parents[x] += self.parents[y] | |
self.parents[y] = x | |
def size(self, x): | |
return -self.parents[self.find(x)] | |
def same(self, x, y): | |
return self.find(x) == self.find(y) | |
def members(self, x): | |
root = self.find(x) | |
return [i for i in range(self.n) if self.find(i) == root] | |
def roots(self): | |
return [i for i, x in enumerate(self.parents) if x < 0] | |
def group_count(self): | |
return len(self.roots()) | |
def all_group_members(self): | |
group_members = defaultdict(list) | |
for member in range(self.n): | |
group_members[self.find(member)].append(member) | |
return group_members | |
def __str__(self): | |
return '\n'.join(f'{r}: {m}' for r, m in self.all_group_members().items()) | |
sys.setrecursionlimit(10 ** 6) # 再帰上限の引き上げ | |
input = sys.stdin.readline | |
INF = 2 ** 63 - 1 | |
N, M = map(int, input().split()) | |
# UnionFindで木構造を作成 | |
uf = UnionFind(N + 1) | |
for i in range(M): | |
A, B = map(int, input().split()) | |
# UnionFindに友達関係を入力 | |
uf.union(A, B) | |
ans = 0 | |
for r, m in uf.all_group_members().items(): | |
if m[0] == 0: | |
continue | |
# 友達集合の最大を求める。最大の友達集合を一人一人分割してしまえば、全てバラける | |
ans = max(ans, len(m)) | |
#print(r, m) # 木構造の確認、デバッグ用 | |
print(ans) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment