結果

問題 No.2290 UnUnion Find
ユーザー hir355hir355
提出日時 2023-05-05 21:37:24
言語 PyPy3
(7.3.15)
結果
RE  
実行時間 -
コード長 1,589 bytes
コンパイル時間 256 ms
コンパイル使用メモリ 82,408 KB
実行使用メモリ 108,112 KB
最終ジャッジ日時 2024-11-23 06:25:32
合計ジャッジ時間 17,430 ms
ジャッジサーバーID
(参考情報)
judge3 / judge1
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample RE * 1
other AC * 2 RE * 44
権限があれば一括ダウンロードができます

ソースコード

diff #

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 x
        else:
            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:
            return
        if self.rank[x] < self.rank[y]:
            self.par[x] = y
            self.size[y] += self.size[x]
        else:
            self.par[y] = x
            self.size[x] += self.size[y]
            if self.rank[x] == self.rank[y]:
                self.rank[x] += 1
 
    def 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 = i
        break
    uf2.unite(que[i][1] - 1, que[i][2] - 1)
else:
    for i in range(n):
        if not uf2.same_check(0, i):
            x = i
uf = 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)
0