結果
問題 | No.2290 UnUnion Find |
ユーザー |
![]() |
提出日時 | 2023-05-05 21:48:33 |
言語 | PyPy3 (7.3.15) |
結果 |
AC
|
実行時間 | 312 ms / 2,000 ms |
コード長 | 1,258 bytes |
コンパイル時間 | 291 ms |
コンパイル使用メモリ | 81,920 KB |
実行使用メモリ | 108,800 KB |
最終ジャッジ日時 | 2024-11-23 06:53:22 |
合計ジャッジ時間 | 17,412 ms |
ジャッジサーバーID (参考情報) |
judge1 / judge5 |
(要ログイン)
ファイルパターン | 結果 |
---|---|
sample | AC * 1 |
other | AC * 46 |
ソースコード
import sysdef main():input = sys.stdin.readlinen, q = map(int, input().split())uf = [-1] * nleaders = set(range(n))def find(x):nonlocal ufy = xwhile uf[x] >= 0: x = uf[x]while uf[y] >= 0:z = uf[y]uf[y] = xy = zreturn xdef union(x, y):nonlocal uf, leadersx, y = find(x), find(y)if x == y: return Falseif uf[x] > uf[y]: x, y = y, xuf[x] += uf[y]uf[y] = xleaders.remove(y)return Trueans = []tmp = Nonefor i in range(q):t, *x = map(int, input().split())if t == 1:a, b = xunion(a - 1, b - 1)else:a = x[0] - 1a = find(a)if len(leaders) == 1:ans.append(-1)else:b = leaders.pop()if b == a:tmp = bb = leaders.pop()ans.append(b + 1)leaders.add(b)if tmp is not None:leaders.add(tmp)tmp = Noneprint('\n'.join(map(str, ans)))if __name__ == '__main__':main()