結果

問題 No.1390 Get together
ユーザー nephrologistnephrologist
提出日時 2021-02-12 22:43:53
言語 PyPy3
(7.3.13)
結果
AC  
実行時間 521 ms / 2,000 ms
コード長 1,420 bytes
コンパイル時間 2,280 ms
コンパイル使用メモリ 86,840 KB
実行使用メモリ 121,380 KB
最終ジャッジ日時 2023-09-27 05:36:32
合計ジャッジ時間 11,180 ms
ジャッジサーバーID
(参考情報)
judge14 / judge11
このコードへのチャレンジ(β)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 63 ms
71,472 KB
testcase_01 AC 66 ms
71,348 KB
testcase_02 AC 64 ms
71,380 KB
testcase_03 AC 118 ms
78,616 KB
testcase_04 AC 110 ms
78,656 KB
testcase_05 AC 112 ms
78,904 KB
testcase_06 AC 110 ms
78,728 KB
testcase_07 AC 104 ms
78,900 KB
testcase_08 AC 108 ms
78,440 KB
testcase_09 AC 126 ms
78,624 KB
testcase_10 AC 63 ms
71,584 KB
testcase_11 AC 64 ms
71,420 KB
testcase_12 AC 63 ms
71,212 KB
testcase_13 AC 64 ms
71,236 KB
testcase_14 AC 66 ms
71,620 KB
testcase_15 AC 65 ms
71,224 KB
testcase_16 AC 250 ms
99,788 KB
testcase_17 AC 354 ms
118,704 KB
testcase_18 AC 245 ms
109,012 KB
testcase_19 AC 521 ms
120,900 KB
testcase_20 AC 483 ms
120,820 KB
testcase_21 AC 497 ms
120,524 KB
testcase_22 AC 372 ms
116,008 KB
testcase_23 AC 385 ms
118,196 KB
testcase_24 AC 385 ms
117,416 KB
testcase_25 AC 479 ms
120,392 KB
testcase_26 AC 470 ms
119,964 KB
testcase_27 AC 479 ms
121,380 KB
testcase_28 AC 481 ms
120,116 KB
testcase_29 AC 476 ms
120,752 KB
testcase_30 AC 472 ms
120,040 KB
testcase_31 AC 476 ms
120,816 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

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

memo = [set() for _ in range(n)]

for _ in range(n):
    b, c = map(int, input().split())
    b, c = b - 1, c - 1
    memo[c].add(b)


class UnionFind:
    # あり本実装
    # rankとrootの配列を1つで賄う方法
    def __init__(self, n):
        self.n = n
        self.par = [-1] * n

    # 根を求める
    def find(self, x):
        if self.par[x] < 0:
            return x
        else:
            self.par[x] = self.find(self.par[x])
            return self.par[x]

    # 同じかどうかの判定
    def is_same(self, x, y):
        return self.find(x) == self.find(y)

    # 集合の大きさ
    def size(self, x):
        return -self.par[self.find(x)]

    # 2つの集合の合体
    # 重みが大きい方に小さい方をつけるようにする
    def unite(self, x, y):
        x = self.find(x)
        y = self.find(y)
        if x == y:
            return False

        if self.par[x] > self.par[y]:
            x, y = y, x
        self.par[x] += self.par[y]
        self.par[y] = x
        return True


UF = UnionFind(m)
ans = 0
for i in range(n):
    temp = list(memo[i])
    if len(temp) >= 2:
        base = temp[0]
        for i in range(len(temp) - 1):
            now = temp[i + 1]
            if UF.is_same(base, now):
                continue
            else:
                UF.unite(base, now)
                ans += 1

print(ans)
0