結果

問題 No.2290 UnUnion Find
ユーザー lllllll88938494
提出日時 2023-05-05 22:07:57
言語 PyPy3
(7.3.15)
結果
WA  
実行時間 -
コード長 1,494 bytes
コンパイル時間 162 ms
コンパイル使用メモリ 81,792 KB
実行使用メモリ 108,800 KB
最終ジャッジ日時 2024-11-23 07:58:55
合計ジャッジ時間 38,177 ms
ジャッジサーバーID
(参考情報)
judge5 / judge4
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 1
other AC * 35 WA * 11
権限があれば一括ダウンロードができます

ソースコード

diff #

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)]
    

n,q= map(int,input().split())
nots = set()
uf = UnionFind(n+1)
for i in range(1,n+1):
    nots.add(i)
s=set()
lis=[]
for i in range(q):
    t = list(map(int,input().split()))
    if t[0] == 1:
        x,y=t[1],t[2]
        if x > y:
            x,y = y,x
        nots.discard(x)
        nots.discard(y)
        uf.union(x,y)
        fx=uf.find(x)
        if fx not in s:
            s.add(x)
            lis.append(x)
    else:
        x=t[1]
        fx=uf.find(x)
        if fx not in s:
            print(x%(n+1) + 1)
        else:
            if uf.size(fx) == n:
                print(-1)
            elif len(nots) > 0:
                for i in nots:
                    print(i)
                    break
            else:
                if lis[0] != fx:
                    print(lis[0])
                else:
                    print(lis[-1])
            
            


0