結果

問題 No.1390 Get together
ユーザー 👑 H20H20
提出日時 2021-04-26 01:33:34
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 498 ms / 2,000 ms
コード長 1,578 bytes
コンパイル時間 294 ms
コンパイル使用メモリ 86,708 KB
実行使用メモリ 98,704 KB
最終ジャッジ日時 2023-09-17 14:34:35
合計ジャッジ時間 10,739 ms
ジャッジサーバーID
(参考情報)
judge14 / judge15
このコードへのチャレンジ(β)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 98 ms
71,560 KB
testcase_01 AC 99 ms
71,584 KB
testcase_02 AC 97 ms
71,420 KB
testcase_03 AC 154 ms
79,008 KB
testcase_04 AC 144 ms
78,564 KB
testcase_05 AC 161 ms
78,564 KB
testcase_06 AC 143 ms
78,592 KB
testcase_07 AC 150 ms
78,376 KB
testcase_08 AC 147 ms
78,592 KB
testcase_09 AC 153 ms
78,772 KB
testcase_10 AC 98 ms
71,496 KB
testcase_11 AC 97 ms
71,632 KB
testcase_12 AC 97 ms
71,444 KB
testcase_13 AC 97 ms
71,644 KB
testcase_14 AC 96 ms
71,532 KB
testcase_15 AC 95 ms
71,416 KB
testcase_16 AC 246 ms
92,800 KB
testcase_17 AC 365 ms
96,600 KB
testcase_18 AC 243 ms
93,092 KB
testcase_19 AC 460 ms
97,936 KB
testcase_20 AC 449 ms
97,104 KB
testcase_21 AC 498 ms
98,704 KB
testcase_22 AC 365 ms
96,608 KB
testcase_23 AC 371 ms
96,784 KB
testcase_24 AC 387 ms
96,836 KB
testcase_25 AC 482 ms
98,236 KB
testcase_26 AC 454 ms
97,580 KB
testcase_27 AC 457 ms
97,660 KB
testcase_28 AC 455 ms
97,384 KB
testcase_29 AC 450 ms
97,536 KB
testcase_30 AC 477 ms
97,972 KB
testcase_31 AC 442 ms
97,960 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

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]:
            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

    def __str__(self):
        return '\n'.join(f'{r}: {m}' for r, m in self.all_group_members().items())


N,M = map(int, input().split())
L = [[] for i in range(N+1)]


for i in range(N):
    b,c = map(int, input().split())
    L[c].append(b)

uf = UnionFind(M+1)
cnt = 0
for l in L:
    for c in l:
        if not uf.same(l[0],c):
            uf.union(l[0],c)
            cnt+=1
print(cnt)
0