結果

問題 No.2418 情報通だよ!Nafmoくん
ユーザー noriocnorioc
提出日時 2023-08-12 15:47:14
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 274 ms / 2,000 ms
コード長 1,496 bytes
コンパイル時間 224 ms
コンパイル使用メモリ 82,160 KB
実行使用メモリ 104,452 KB
最終ジャッジ日時 2024-04-30 10:13:17
合計ジャッジ時間 5,151 ms
ジャッジサーバーID
(参考情報)
judge4 / judge1
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 45 ms
54,384 KB
testcase_01 AC 43 ms
54,116 KB
testcase_02 AC 43 ms
54,068 KB
testcase_03 AC 232 ms
95,968 KB
testcase_04 AC 119 ms
100,468 KB
testcase_05 AC 235 ms
80,408 KB
testcase_06 AC 185 ms
97,220 KB
testcase_07 AC 226 ms
78,864 KB
testcase_08 AC 189 ms
104,452 KB
testcase_09 AC 255 ms
81,576 KB
testcase_10 AC 244 ms
94,132 KB
testcase_11 AC 212 ms
92,008 KB
testcase_12 AC 179 ms
91,248 KB
testcase_13 AC 162 ms
80,616 KB
testcase_14 AC 193 ms
86,620 KB
testcase_15 AC 120 ms
76,900 KB
testcase_16 AC 274 ms
85,308 KB
testcase_17 AC 138 ms
77,976 KB
testcase_18 AC 167 ms
94,688 KB
testcase_19 AC 111 ms
97,804 KB
testcase_20 AC 136 ms
76,980 KB
testcase_21 AC 164 ms
82,768 KB
testcase_22 AC 180 ms
78,172 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

from collections import defaultdict


class UnionFind:
    def __init__(self, n):
        self.data = [-1] * (n + 1)
        self.nexts = [-1] * (n + 1)  # 次の要素(なければ-1)
        self.tails = list(range(n + 1))  # 末尾の要素

    def root(self, a: int) -> int:
        if self.data[a] < 0: return a
        self.data[a] = self.root(self.data[a])
        return self.data[a]

    def unite(self, a: int, b: int) -> bool:
        pa = self.root(a)
        pb = self.root(b)
        if pa == pb: return False
        if self.data[pa] > self.data[pb]:
            pa, pb = pb, pa
        self.data[pa] += self.data[pb] # pa を pb をつなげる
        self.data[pb] = pa
        # pa の末尾に pb を繋げる
        self.nexts[self.tails[pa]] = pb
        self.tails[pa] = self.tails[pb]
        return True

    def issame(self, a: int, b: int) -> bool:
        return self.root(a) == self.root(b)

    def size(self, a: int) -> int:
        """a が属する集合のサイズ"""
        return -self.data[self.root(a)]

    def group(self, a):
        """a が属する集合"""
        v = self.root(a)
        while v != -1:
            yield v
            v = self.nexts[v]


N, M = map(int, input().split())
uf = UnionFind(2 * N)
for _ in range(M):
    A, B = map(lambda x: int(x)-1, input().split())
    uf.unite(A, B)

used = set()
ans = N
for i in range(2 * N):
    p = uf.root(i)
    if p in used: continue
    used.add(p)
    ans -= uf.size(i) // 2

print(ans)
0