結果

問題 No.556 仁義なきサルたち
ユーザー momotaros300momotaros300
提出日時 2019-09-07 20:52:01
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 207 ms / 2,000 ms
コード長 1,436 bytes
コンパイル時間 1,511 ms
コンパイル使用メモリ 86,452 KB
実行使用メモリ 79,964 KB
最終ジャッジ日時 2023-09-09 11:12:42
合計ジャッジ時間 5,211 ms
ジャッジサーバーID
(参考情報)
judge13 / judge11
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 70 ms
71,284 KB
testcase_01 AC 71 ms
70,964 KB
testcase_02 AC 71 ms
70,960 KB
testcase_03 AC 70 ms
71,140 KB
testcase_04 AC 69 ms
71,080 KB
testcase_05 AC 72 ms
71,068 KB
testcase_06 AC 73 ms
71,144 KB
testcase_07 AC 84 ms
75,336 KB
testcase_08 AC 78 ms
75,800 KB
testcase_09 AC 84 ms
75,764 KB
testcase_10 AC 92 ms
76,168 KB
testcase_11 AC 103 ms
76,304 KB
testcase_12 AC 96 ms
76,348 KB
testcase_13 AC 90 ms
76,556 KB
testcase_14 AC 137 ms
78,232 KB
testcase_15 AC 160 ms
79,008 KB
testcase_16 AC 129 ms
78,252 KB
testcase_17 AC 160 ms
78,724 KB
testcase_18 AC 207 ms
79,964 KB
testcase_19 AC 119 ms
77,992 KB
testcase_20 AC 122 ms
78,052 KB
testcase_21 AC 122 ms
77,864 KB
権限があれば一括ダウンロードができます

ソースコード

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