結果

問題 No.556 仁義なきサルたち
ユーザー irumo8202irumo8202
提出日時 2022-01-26 17:05:50
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 197 ms / 2,000 ms
コード長 1,465 bytes
コンパイル時間 1,506 ms
コンパイル使用メモリ 86,844 KB
実行使用メモリ 79,016 KB
最終ジャッジ日時 2023-08-24 22:27:22
合計ジャッジ時間 5,708 ms
ジャッジサーバーID
(参考情報)
judge12 / judge13
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 88 ms
71,504 KB
testcase_01 AC 89 ms
71,700 KB
testcase_02 AC 89 ms
71,684 KB
testcase_03 AC 89 ms
71,852 KB
testcase_04 AC 90 ms
71,412 KB
testcase_05 AC 91 ms
71,616 KB
testcase_06 AC 92 ms
71,460 KB
testcase_07 AC 96 ms
72,300 KB
testcase_08 AC 96 ms
72,368 KB
testcase_09 AC 102 ms
76,352 KB
testcase_10 AC 109 ms
76,628 KB
testcase_11 AC 113 ms
77,364 KB
testcase_12 AC 114 ms
77,120 KB
testcase_13 AC 111 ms
77,528 KB
testcase_14 AC 152 ms
79,016 KB
testcase_15 AC 165 ms
78,320 KB
testcase_16 AC 141 ms
78,192 KB
testcase_17 AC 167 ms
78,300 KB
testcase_18 AC 197 ms
78,392 KB
testcase_19 AC 133 ms
77,956 KB
testcase_20 AC 134 ms
78,472 KB
testcase_21 AC 136 ms
78,360 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

N, M = map(int, input().split())

from collections import defaultdict


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]:
            if x > y:
                x, y = y, x
        elif 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)]

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

    def members(self, x):
        root = self.find(x)
        return [i for i in range(self.n) if self.find(i) == root]

    def roots(self):
        return [i for i, x in enumerate(self.parents) if x < 0]

    def group_count(self):
        return len(self.roots())

    def all_group_members(self):
        group_members = defaultdict(list)
        for member in range(self.n):
            group_members[self.find(member)].append(member)
        return group_members


uf = UnionFind(N + 1)

for i in range(M):
    A, B = map(int, input().split())
    uf.union(A, B)

for i in range(1, N + 1):
    print(uf.find(i))
0