結果

問題 No.556 仁義なきサルたち
ユーザー maspymaspy
提出日時 2020-02-28 14:31:39
言語 Python3
(3.12.2 + numpy 1.26.4 + scipy 1.12.0)
結果
AC  
実行時間 31 ms / 2,000 ms
コード長 1,052 bytes
コンパイル時間 1,057 ms
コンパイル使用メモリ 10,940 KB
実行使用メモリ 10,120 KB
最終ジャッジ日時 2023-08-03 19:17:49
合計ジャッジ時間 2,049 ms
ジャッジサーバーID
(参考情報)
judge15 / judge13
このコードへのチャレンジ(β)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 16 ms
8,144 KB
testcase_01 AC 16 ms
8,264 KB
testcase_02 AC 16 ms
8,264 KB
testcase_03 AC 16 ms
7,928 KB
testcase_04 AC 16 ms
8,312 KB
testcase_05 AC 17 ms
8,184 KB
testcase_06 AC 16 ms
8,176 KB
testcase_07 AC 16 ms
8,228 KB
testcase_08 AC 17 ms
8,212 KB
testcase_09 AC 17 ms
8,340 KB
testcase_10 AC 17 ms
8,252 KB
testcase_11 AC 18 ms
8,444 KB
testcase_12 AC 17 ms
8,416 KB
testcase_13 AC 19 ms
8,844 KB
testcase_14 AC 21 ms
8,976 KB
testcase_15 AC 22 ms
8,800 KB
testcase_16 AC 23 ms
9,260 KB
testcase_17 AC 25 ms
9,588 KB
testcase_18 AC 31 ms
10,120 KB
testcase_19 AC 29 ms
9,236 KB
testcase_20 AC 31 ms
9,696 KB
testcase_21 AC 30 ms
9,704 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

#!/usr/bin/env python3
# %%
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines


# %%
N, M = map(int, readline().split())
m = map(int, read().split())
AB = zip(m, m)


# %%
class UnionFind:
    def __init__(self, N):
        self.root = list(range(N))
        self.size = [1] * (N)

    def find_root(self, x):
        root = self.root
        while root[x] != x:
            root[x] = root[root[x]]
            x = root[x]
        return x

    def merge(self, x, y):
        x = self.find_root(x)
        y = self.find_root(y)
        if x == y:
            return False
        if x > y:
            x, y = y, x
        sx, sy = self.size[x], self.size[y]
        if sx < sy:
            self.root[x] = y
            self.size[y] += sx
        else:
            self.root[y] = x
            self.size[x] += sy
        return True


# %%
uf = UnionFind(N + 1)
for a, b in AB:
    uf.merge(a, b)


# %%
boss = (uf.find_root(x) for x in range(1, N + 1))
print('\n'.join(map(str, boss)))
0