結果

問題 No.1390 Get together
ユーザー brthyyjpbrthyyjp
提出日時 2021-02-14 13:29:28
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 591 ms / 2,000 ms
コード長 1,446 bytes
コンパイル時間 283 ms
コンパイル使用メモリ 87,176 KB
実行使用メモリ 118,896 KB
最終ジャッジ日時 2023-09-29 03:13:42
合計ジャッジ時間 13,674 ms
ジャッジサーバーID
(参考情報)
judge13 / judge14
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 75 ms
71,508 KB
testcase_01 AC 74 ms
71,392 KB
testcase_02 AC 74 ms
71,552 KB
testcase_03 AC 128 ms
78,576 KB
testcase_04 AC 118 ms
78,560 KB
testcase_05 AC 122 ms
78,332 KB
testcase_06 AC 120 ms
78,976 KB
testcase_07 AC 114 ms
78,588 KB
testcase_08 AC 119 ms
78,652 KB
testcase_09 AC 129 ms
79,224 KB
testcase_10 AC 73 ms
71,132 KB
testcase_11 AC 74 ms
71,596 KB
testcase_12 AC 74 ms
71,364 KB
testcase_13 AC 74 ms
71,484 KB
testcase_14 AC 74 ms
71,304 KB
testcase_15 AC 75 ms
71,404 KB
testcase_16 AC 295 ms
111,856 KB
testcase_17 AC 282 ms
111,788 KB
testcase_18 AC 247 ms
115,440 KB
testcase_19 AC 591 ms
118,896 KB
testcase_20 AC 576 ms
115,684 KB
testcase_21 AC 561 ms
115,424 KB
testcase_22 AC 446 ms
117,200 KB
testcase_23 AC 450 ms
116,804 KB
testcase_24 AC 457 ms
116,800 KB
testcase_25 AC 541 ms
118,248 KB
testcase_26 AC 564 ms
118,472 KB
testcase_27 AC 573 ms
118,544 KB
testcase_28 AC 566 ms
118,592 KB
testcase_29 AC 537 ms
117,444 KB
testcase_30 AC 544 ms
118,116 KB
testcase_31 AC 576 ms
118,652 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

class UnionFind:
    def __init__(self, n):
        self.par = [-1]*n
        self.rank = [0]*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 Unite(self, x, y):
        x = self.Find(x)
        y = self.Find(y)

        if x != y:
            if self.rank[x] < self.rank[y]:
                self.par[y] += self.par[x]
                self.par[x] = y
            else:
                self.par[x] += self.par[y]
                self.par[y] = x
                if self.rank[x] == self.rank[y]:
                    self.rank[x] += 1

    def Same(self, x, y):
        return self.Find(x) == self.Find(y)

    def Size(self, x):
        return -self.par[self.Find(x)]

import sys
import io, os
input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline

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

B = [[] for i in range(m)]
C = [[] for i in range(n)]

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

uf = UnionFind(n)
for i in range(m):
    if len(B[i]) <= 1:
        continue
    for j in range(len(B[i])-1):
        uf.Unite(B[i][j], B[i][j+1])
ans = 0
for i in range(n):
    if len(C[i]) <= 1:
        continue
    for j in range(1, len(C[i])):
        if not uf.Same(C[i][0], C[i][j]):
            ans += 1
            uf.Unite(C[i][0], C[i][j])
print(ans)
0