結果

問題 No.1390 Get together
ユーザー so4649so4649
提出日時 2021-02-12 21:34:03
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 497 ms / 2,000 ms
コード長 1,606 bytes
コンパイル時間 691 ms
コンパイル使用メモリ 87,056 KB
実行使用メモリ 98,720 KB
最終ジャッジ日時 2023-09-27 03:07:23
合計ジャッジ時間 11,011 ms
ジャッジサーバーID
(参考情報)
judge14 / judge15
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 78 ms
71,340 KB
testcase_01 AC 84 ms
71,296 KB
testcase_02 AC 79 ms
71,392 KB
testcase_03 AC 159 ms
78,140 KB
testcase_04 AC 128 ms
77,904 KB
testcase_05 AC 124 ms
77,816 KB
testcase_06 AC 125 ms
77,772 KB
testcase_07 AC 126 ms
78,488 KB
testcase_08 AC 126 ms
78,124 KB
testcase_09 AC 136 ms
78,120 KB
testcase_10 AC 80 ms
71,268 KB
testcase_11 AC 79 ms
71,216 KB
testcase_12 AC 78 ms
71,344 KB
testcase_13 AC 79 ms
71,428 KB
testcase_14 AC 78 ms
71,220 KB
testcase_15 AC 79 ms
71,344 KB
testcase_16 AC 236 ms
93,816 KB
testcase_17 AC 351 ms
96,164 KB
testcase_18 AC 231 ms
93,756 KB
testcase_19 AC 466 ms
97,428 KB
testcase_20 AC 465 ms
97,420 KB
testcase_21 AC 481 ms
97,708 KB
testcase_22 AC 351 ms
96,244 KB
testcase_23 AC 389 ms
96,044 KB
testcase_24 AC 387 ms
96,668 KB
testcase_25 AC 468 ms
98,076 KB
testcase_26 AC 453 ms
97,792 KB
testcase_27 AC 469 ms
97,912 KB
testcase_28 AC 497 ms
98,720 KB
testcase_29 AC 483 ms
98,380 KB
testcase_30 AC 443 ms
97,500 KB
testcase_31 AC 447 ms
97,156 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

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):
        self.group = {r:[] for r in self.roots()}
        for i in range(self.n):
            self.group[self.find(i)].append(i)
        return self.group

    def __str__(self):
        return '\n'.join('{}: {}'.format(r, self.all_group_members()[r]) for r in self.roots())


n,m = map(int,input().split())

a = [[] for i in range(n)]
for i in range(n):
    b,c = map(int,input().split())
    a[c-1].append(b-1)

uf = UnionFind(m)
ans = 0
for g in a:
    x = len(g)
    if x >= 2:
        for i in range(x-1):
            if not uf.same(g[i],g[i+1]):
                ans += 1
                uf.union(g[i],g[i+1])

print(ans)
0