結果

問題 No.1390 Get together
ユーザー H3PO4H3PO4
提出日時 2021-02-12 21:36:17
言語 PyPy3
(7.3.13)
結果
AC  
実行時間 377 ms / 2,000 ms
コード長 1,548 bytes
コンパイル時間 285 ms
コンパイル使用メモリ 87,212 KB
実行使用メモリ 117,728 KB
最終ジャッジ日時 2023-09-27 03:11:46
合計ジャッジ時間 8,743 ms
ジャッジサーバーID
(参考情報)
judge14 / judge12
このコードへのチャレンジ(β)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 92 ms
71,804 KB
testcase_01 AC 94 ms
71,308 KB
testcase_02 AC 92 ms
71,608 KB
testcase_03 AC 118 ms
77,796 KB
testcase_04 AC 115 ms
77,760 KB
testcase_05 AC 121 ms
77,904 KB
testcase_06 AC 117 ms
77,948 KB
testcase_07 AC 111 ms
77,928 KB
testcase_08 AC 116 ms
77,624 KB
testcase_09 AC 121 ms
77,952 KB
testcase_10 AC 91 ms
71,616 KB
testcase_11 AC 93 ms
71,796 KB
testcase_12 AC 94 ms
71,688 KB
testcase_13 AC 93 ms
71,304 KB
testcase_14 AC 92 ms
71,900 KB
testcase_15 AC 91 ms
71,672 KB
testcase_16 AC 165 ms
89,360 KB
testcase_17 AC 253 ms
117,376 KB
testcase_18 AC 157 ms
86,104 KB
testcase_19 AC 340 ms
113,008 KB
testcase_20 AC 377 ms
117,588 KB
testcase_21 AC 357 ms
117,728 KB
testcase_22 AC 258 ms
103,928 KB
testcase_23 AC 254 ms
104,612 KB
testcase_24 AC 264 ms
104,700 KB
testcase_25 AC 337 ms
113,368 KB
testcase_26 AC 326 ms
113,204 KB
testcase_27 AC 327 ms
112,996 KB
testcase_28 AC 337 ms
113,380 KB
testcase_29 AC 335 ms
113,032 KB
testcase_30 AC 326 ms
113,248 KB
testcase_31 AC 368 ms
113,892 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

import sys
from collections import defaultdict

input = sys.stdin.buffer.readline


class UnionFind:
    def __init__(self, n):
        self.n = n
        self.parent = [i for i in range(n)]
        self.height = [1] * n
        self.size = [1] * n

    def find(self, x):
        if self.parent[x] == x:
            return x
        else:
            self.parent[x] = self.find(self.parent[x])
            return self.parent[x]

    def unite(self, x, y):
        x = self.find(x)
        y = self.find(y)
        if x != y:
            if self.height[x] < self.height[y]:
                self.parent[x] = y
                self.size[y] += self.size[x]
            else:
                self.parent[y] = x
                self.size[x] += self.size[y]
                if self.height[x] == self.height[y]:
                    self.height[x] += 1

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

    def group_size(self, x):
        return self.size[self.find(x)]

    def group_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.parent) if i == x]

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


N, M = map(int, input().split())
d = defaultdict(list)
for _ in range(N):
    b, c = map(int, input().split())
    b -= 1
    d[c].append(b)
d = dict(d)
uf = UnionFind(M)
for v in d.values():
    for i in range(len(v) - 1):
        uf.unite(v[i], v[i + 1])
print(M - uf.group_count())
0