結果

問題 No.2290 UnUnion Find
ユーザー 学ぶマン
提出日時 2025-02-22 18:50:45
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 661 ms / 2,000 ms
コード長 3,095 bytes
コンパイル時間 1,151 ms
コンパイル使用メモリ 81,912 KB
実行使用メモリ 114,716 KB
最終ジャッジ日時 2025-02-22 18:51:16
合計ジャッジ時間 28,555 ms
ジャッジサーバーID
(参考情報)
judge5 / judge1
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 1
other AC * 46
権限があれば一括ダウンロードができます

ソースコード

diff #

from collections import defaultdict

class UnionFind():
    def __init__(self, n):
        self.n = n
        self.parents = [-1] * n
        self.link = [i for i in range(n)]
        self.score = [0] * 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):
        rootx = self.find(x)
        rooty = self.find(y)

        if rootx == rooty: # すでに same ならなにもしない!
            return

        if self.parents[rootx] > self.parents[rooty]: # -3 > -4 のようなケース(前者の方が軍勢が少ない)
            rootx, rooty = rooty, rootx # rootx = 多い, rooty = 少ない の順番に変更

        # 統合(rootx が新しい棟梁, rooty は軍門に下った)
        self.parents[rootx] += self.parents[rooty] # 多い方(rootx)に併合する
        self.parents[rooty] = rootx

        self.link[x], self.link[y] = self.link[y], self.link[x]
        self.score[rootx] += self.score[rooty]
        self.score[rooty] = 0

    def size(self, x): # O(1)
        return -self.parents[self.find(x)]

    def same(self, x, y): # O(1)
        return self.find(x) == self.find(y)

    def members(self, x): # O(K: 集合の要素数) 最小で1、最大でN
        res = [x]
        now = self.link[x]
        while now != x:
            res.append(now)
            now = self.link[now]
        return res

    def roots(self): # O(N)
        return [i for i, x in enumerate(self.parents) if x < 0]

    def group_count(self): # roots() の呼び出しは全頂点の par をチェックする=遅いため、N回使うと TLE する
        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)
root_set = set([i for i in range(N)])
ansl = []
for i in range(Q):
    q = list(map(int, input().split()))
    if q[0] == 1:
        _, u, v = q
        u -= 1
        v -= 1
        if uf.same(u, v):
            continue
        root_u = uf.find(u)
        root_v = uf.find(v)
        uf.union(u, v)
        new_root = uf.find(u)

        if new_root == root_u:
            root_set.remove(root_v)
        else:
            root_set.remove(root_u)

    else:
        _, v = q
        v -= 1
        # root_set 1個なら諦める
        if len(root_set) == 1:
            ansl.append(-1)
            continue
        # 1個取り出す
        someone = root_set.pop()
        # 自分のrootならもう一個取り出す
        if someone == uf.find(v):
            other = root_set.pop()
            ansl.append(other + 1)
            root_set.add(other)
        else:
            ansl.append(someone + 1)
        root_set.add(someone)

print(*ansl,sep='\n')
0