結果
| 問題 |
No.2290 UnUnion Find
|
| コンテスト | |
| ユーザー |
|
| 提出日時 | 2023-05-17 09:44:36 |
| 言語 | PyPy3 (7.3.15) |
| 結果 |
TLE
|
| 実行時間 | - |
| コード長 | 1,239 bytes |
| コンパイル時間 | 389 ms |
| コンパイル使用メモリ | 81,840 KB |
| 実行使用メモリ | 348,192 KB |
| 最終ジャッジ日時 | 2024-12-15 05:17:14 |
| 合計ジャッジ時間 | 140,454 ms |
|
ジャッジサーバーID (参考情報) |
judge1 / judge5 |
(要ログイン)
| ファイルパターン | 結果 |
|---|---|
| sample | AC * 1 |
| other | AC * 2 TLE * 44 |
ソースコード
import sys
input = sys.stdin.readline
def main():
N, Q = map(int, input().split())
uf = UnionFind(N)
ans = []
total = set(range(N))
for _ in range(Q):
query = list(map(int, input().split()))
if query[0] == 1:
u, v = query[1:]
u, v = u - 1, v - 1
uf.union(u, v)
else:
v = query[1] - 1
u = uf.find(v)
res = total - uf.groups[u]
ans.append(res.pop() + 1 if res else -1)
print(*ans, sep='\n')
class UnionFind:
def __init__(self, n):
self.parent = [-1] * n
self.groups = dict()
for i in range(n):
self.groups[i] = {i}
def find(self, x):
if self.parent[x] < 0:
return x
self.parent[x] = self.find(self.parent[x])
return self.parent[x]
def union(self, x, y):
x, y = self.find(x), self.find(y)
if x == y:
return
if self.parent[y] < self.parent[x]:
x, y = y, x
self.parent[x] += self.parent[y]
self.parent[y] = x
self.groups[x] |= self.groups[y]
del self.groups[y]
def same(self, x, y):
return self.find(x) == self.find(y)
main()