結果

問題 No.556 仁義なきサルたち
ユーザー momotaros300momotaros300
提出日時 2019-09-07 19:42:10
言語 PyPy3
(7.3.15)
結果
WA  
実行時間 -
コード長 1,322 bytes
コンパイル時間 558 ms
コンパイル使用メモリ 86,916 KB
実行使用メモリ 79,788 KB
最終ジャッジ日時 2023-09-09 09:17:33
合計ジャッジ時間 4,006 ms
ジャッジサーバーID
(参考情報)
judge15 / judge12
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 68 ms
71,152 KB
testcase_01 AC 68 ms
71,028 KB
testcase_02 WA -
testcase_03 WA -
testcase_04 WA -
testcase_05 WA -
testcase_06 WA -
testcase_07 WA -
testcase_08 WA -
testcase_09 WA -
testcase_10 WA -
testcase_11 WA -
testcase_12 WA -
testcase_13 WA -
testcase_14 WA -
testcase_15 WA -
testcase_16 WA -
testcase_17 WA -
testcase_18 WA -
testcase_19 AC 113 ms
77,912 KB
testcase_20 WA -
testcase_21 WA -
権限があれば一括ダウンロードができます

ソースコード

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 self.id[s1] <= self.id[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))
    if uf.id[uf.root(s-1)] == uf.id[uf.root(t-1)]:
        uf.union(s-1,t-1,0)
    elif uf.id[uf.root(s-1)]<uf.id[uf.root(t-1)]:
        uf.union(s-1,t-1,1)
    else:
        uf.union(t-1,s-1,1)

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