結果

問題 No.556 仁義なきサルたち
ユーザー momotaros300
提出日時 2019-09-07 20:52:01
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 188 ms / 2,000 ms
コード長 1,436 bytes
コンパイル時間 308 ms
コンパイル使用メモリ 82,560 KB
実行使用メモリ 79,212 KB
最終ジャッジ日時 2024-06-27 04:20:19
合計ジャッジ時間 3,125 ms
ジャッジサーバーID
(参考情報)
judge5 / judge2
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
other AC * 22
権限があれば一括ダウンロードができます

ソースコード

diff #

n,m=map(int,input().split())
query=[tuple(map(int,input().split())) for i in range(m)]


class UnionFind:
    __slots__ = ['id', 'size']

    def __init__(self, n):
        self.id = [-1] * n
        self.size = n

    def root(self, x):
        if self.id[x] < 0:
            return x
        else:
            self.id[x] = self.root(self.id[x])
            return self.id[x]

    def find(self, x, y):
        return self.root(x) == self.root(y)

    def union(self, x, y, b):
        s1, s2 = self.root(x), self.root(y)
        if b==0:
            if s1 != s2:
                if s1 <= s2:
                    self.id[s1] += self.id[s2]
                    self.id[s2] = s1
                else:
                    self.id[s2] += self.id[s1]
                    self.id[s1] = s2
                self.size -= 1
            return True
        else:
            self.id[s1] += self.id[s2]
            self.id[s2] = s1            
        return False

            
uf = UnionFind(n)

for s,t in query:
    # print(s,t)
    # print(uf.root(s-1),uf.root(t-1))
    # for i in range(n):
    #    print(uf.root(i)+1, end='')
    # print()
    if uf.id[uf.root(s-1)] == uf.id[uf.root(t-1)]:
        uf.union(uf.root(s-1),uf.root(t-1),0)
    elif uf.id[uf.root(s-1)]<uf.id[uf.root(t-1)]:
        uf.union(uf.root(s-1),uf.root(t-1),1)
    else:
        uf.union(uf.root(t-1),uf.root(s-1),1)

for i in range(n):
    print(uf.root(i)+1)

    
0