結果
問題 | No.2290 UnUnion Find |
ユーザー |
![]() |
提出日時 | 2023-05-05 21:37:55 |
言語 | PyPy3 (7.3.15) |
結果 |
AC
|
実行時間 | 875 ms / 2,000 ms |
コード長 | 1,613 bytes |
コンパイル時間 | 390 ms |
コンパイル使用メモリ | 82,176 KB |
実行使用メモリ | 115,496 KB |
最終ジャッジ日時 | 2024-11-23 06:27:33 |
合計ジャッジ時間 | 31,476 ms |
ジャッジサーバーID (参考情報) |
judge1 / judge2 |
(要ログイン)
ファイルパターン | 結果 |
---|---|
sample | AC * 1 |
other | AC * 46 |
ソースコード
class UnionFind:def __init__(self, n):self.par = [i for i in range(n+1)]self.rank = [0] * (n + 1)self.size = [1] * (n + 1)def find(self, x):if self.par[x] == x:return xelse:self.par[x] = self.find(self.par[x])return self.par[x]def unite(self, x, y):x = self.find(x)y = self.find(y)if x == y:returnif self.rank[x] < self.rank[y]:self.par[x] = yself.size[y] += self.size[x]else:self.par[y] = xself.size[x] += self.size[y]if self.rank[x] == self.rank[y]:self.rank[x] += 1def same_check(self, x, y):return self.find(x) == self.find(y)n, q = map(int, input().split())que = [list(map(int, input().split())) for _ in range(q)]uf = UnionFind(n)uf2 = UnionFind(n)for i in range(q):if que[i][0] == 1:uf.unite(que[i][1] - 1, que[i][2] - 1)if uf.size[uf.find(0)] == n:for i in range(n):if not uf2.same_check(0, i):x = ibreakuf2.unite(que[i][1] - 1, que[i][2] - 1)else:for i in range(n):if not uf2.same_check(0, i):x = iuf = UnionFind(n)for i in range(q):if que[i][0] == 1:uf.unite(que[i][1] - 1, que[i][2] - 1)else:if uf.same_check(que[i][1] - 1, 0):if uf.same_check(que[i][1] - 1, x):print(-1)else:print(x + 1)else:print(1)