結果
問題 | No.556 仁義なきサルたち |
ユーザー |
![]() |
提出日時 | 2021-02-25 05:28:51 |
言語 | PyPy3 (7.3.15) |
結果 |
AC
|
実行時間 | 127 ms / 2,000 ms |
コード長 | 1,418 bytes |
コンパイル時間 | 535 ms |
コンパイル使用メモリ | 82,016 KB |
実行使用メモリ | 77,660 KB |
最終ジャッジ日時 | 2024-09-25 05:10:21 |
合計ジャッジ時間 | 2,345 ms |
ジャッジサーバーID (参考情報) |
judge1 / judge5 |
(要ログイン)
ファイルパターン | 結果 |
---|---|
other | AC * 22 |
ソースコード
class UnionFind:def __init__(self, n):self.parent = list(range(n)) #親ノードself.size = [1]*n #グループの要素数self.top = list(range(n)) #グループの要素数def root(self, x): #root(x): xの根ノードを返す.while self.parent[x] != x:self.parent[x] = self.parent[self.parent[x]]x = self.parent[x]return xdef merge(self, x, y): #merge(x,y): xのいる組とyのいる組をまとめるx, y = self.root(x), self.root(y)if x == y: return Falseif self.size[x] < self.size[y] or (self.size[x] == self.size[y] and self.top[x] > self.top[y]):self.top[x] = self.top[y]else:self.top[y] = self.top[x]if self.size[x] < self.size[y]: x,y=y,x #xの要素数が大きいようにself.size[x] += self.size[y] #xの要素数を更新self.parent[y] = x #yをxにつなぐreturn Truedef issame(self, x, y): #same(x,y): xとyが同じ組ならTruereturn self.root(x) == self.root(y)def getsize(self,x): #size(x): xのいるグループの要素数を返すreturn self.size[self.root(x)]n,m = map(int,input().split())UF = UnionFind(n)top = list(range(n))for _ in range(m):a,b = map(int,input().split())UF.merge(a-1,b-1)for i in range(n):print(UF.top[UF.root(i)]+1)