結果

問題 No.2290 UnUnion Find
ユーザー yabityabit
提出日時 2023-06-30 14:09:59
言語 PyPy3
(7.3.15)
結果
TLE  
実行時間 -
コード長 1,852 bytes
コンパイル時間 1,621 ms
コンパイル使用メモリ 85,644 KB
実行使用メモリ 78,144 KB
最終ジャッジ日時 2023-09-21 07:39:53
合計ジャッジ時間 12,943 ms
ジャッジサーバーID
(参考情報)
judge15 / judge14
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 95 ms
71,520 KB
testcase_01 AC 104 ms
71,548 KB
testcase_02 AC 764 ms
78,144 KB
testcase_03 TLE -
testcase_04 -- -
testcase_05 -- -
testcase_06 -- -
testcase_07 -- -
testcase_08 -- -
testcase_09 -- -
testcase_10 -- -
testcase_11 -- -
testcase_12 -- -
testcase_13 -- -
testcase_14 -- -
testcase_15 -- -
testcase_16 -- -
testcase_17 -- -
testcase_18 -- -
testcase_19 -- -
testcase_20 -- -
testcase_21 -- -
testcase_22 -- -
testcase_23 -- -
testcase_24 -- -
testcase_25 -- -
testcase_26 -- -
testcase_27 -- -
testcase_28 -- -
testcase_29 -- -
testcase_30 -- -
testcase_31 -- -
testcase_32 -- -
testcase_33 -- -
testcase_34 -- -
testcase_35 -- -
testcase_36 -- -
testcase_37 -- -
testcase_38 -- -
testcase_39 -- -
testcase_40 -- -
testcase_41 -- -
testcase_42 -- -
testcase_43 -- -
testcase_44 -- -
testcase_45 -- -
testcase_46 -- -
権限があれば一括ダウンロードができます

ソースコード

diff #

from collections import defaultdict
 # UnionFind(n) n:頂点数
 # parents:i番目の点が属する根 それ自身が根なら-1
 # find(x):xの属する根を再帰的に求める
 # unite(x,y):多い木に小さい木を結合
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())

N,Q = map(int, input().split())
uf = UnionFind(N)
roots = set(range(N))
for q in range(Q):
    L = list(map(int, input().split()))
    if L[0] == 1:
        uf.union(L[1]-1, L[2]-1)
        roots.discard(uf.find(L[1]-1))
    else:
        ret = -1
        for r in roots:
            if not uf.same(r, L[1]-1):
                ret = r+1
                break
        print(ret)
0