結果

問題 No.1390 Get together
ユーザー O2MTO2MT
提出日時 2021-02-13 13:49:37
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 519 ms / 2,000 ms
コード長 1,562 bytes
コンパイル時間 1,864 ms
コンパイル使用メモリ 86,576 KB
実行使用メモリ 146,536 KB
最終ジャッジ日時 2023-09-27 22:13:50
合計ジャッジ時間 11,554 ms
ジャッジサーバーID
(参考情報)
judge13 / judge14
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 95 ms
71,616 KB
testcase_01 AC 93 ms
71,676 KB
testcase_02 AC 96 ms
71,588 KB
testcase_03 AC 153 ms
78,972 KB
testcase_04 AC 149 ms
78,948 KB
testcase_05 AC 152 ms
79,260 KB
testcase_06 AC 147 ms
78,880 KB
testcase_07 AC 146 ms
79,552 KB
testcase_08 AC 149 ms
78,772 KB
testcase_09 AC 158 ms
79,104 KB
testcase_10 AC 95 ms
71,732 KB
testcase_11 AC 93 ms
71,440 KB
testcase_12 AC 94 ms
71,444 KB
testcase_13 AC 94 ms
71,780 KB
testcase_14 AC 96 ms
71,532 KB
testcase_15 AC 93 ms
71,416 KB
testcase_16 AC 279 ms
113,544 KB
testcase_17 AC 424 ms
146,536 KB
testcase_18 AC 260 ms
106,432 KB
testcase_19 AC 515 ms
118,132 KB
testcase_20 AC 519 ms
137,536 KB
testcase_21 AC 497 ms
126,764 KB
testcase_22 AC 394 ms
116,148 KB
testcase_23 AC 393 ms
118,372 KB
testcase_24 AC 394 ms
118,552 KB
testcase_25 AC 512 ms
116,932 KB
testcase_26 AC 495 ms
115,904 KB
testcase_27 AC 506 ms
118,840 KB
testcase_28 AC 500 ms
117,920 KB
testcase_29 AC 505 ms
117,496 KB
testcase_30 AC 506 ms
118,128 KB
testcase_31 AC 502 ms
116,560 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
 

N,M = map(int,input().split())
S = max(N,M)
l = [[] for _ in range(S)]
uf = UnionFind(S)

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

for i in range(S):
    for j in range(len(l[i])-1):
        uf.union(l[i][j],l[i][j+1])

A = list(uf.all_group_members().values())
group_cnt = len(A)
ans = S-group_cnt
print(ans)
0