結果

問題 No.1390 Get together
ユーザー norioc
提出日時 2025-02-18 01:26:43
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 505 ms / 2,000 ms
コード長 1,508 bytes
コンパイル時間 297 ms
コンパイル使用メモリ 82,308 KB
実行使用メモリ 155,760 KB
最終ジャッジ日時 2025-02-18 01:26:55
合計ジャッジ時間 10,960 ms
ジャッジサーバーID
(参考情報)
judge2 / judge4
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 3
other AC * 29
権限があれば一括ダウンロードができます

ソースコード

diff #
プレゼンテーションモードにする

from collections import defaultdict
class UnionFind:
def __init__(self, n: int):
self.data = [-1] * (n+1)
self.nexts = [i for i in range(n+1)]
def root(self, a: int) -> int:
if self.data[a] < 0: return a
self.data[a] = self.root(self.data[a])
return self.data[a]
def unite(self, a: int, b: int) -> bool:
pa = self.root(a)
pb = self.root(b)
if pa == pb: return False
if self.data[pa] > self.data[pb]:
pa, pb = pb, pa
self.data[pa] += self.data[pb] # pa pb
self.data[pb] = pa
self.nexts[pa], self.nexts[pb] = self.nexts[pb], self.nexts[pa]
return True
def issame(self, a: int, b: int) -> bool:
return self.root(a) == self.root(b)
def size(self, a: int) -> int:
"""a """
return -self.data[self.root(a)]
def group(self, a: int):
"""a """
yield a
x = a
while self.nexts[x] != a:
x = self.nexts[x]
yield x
N, M = map(int, input().split())
freq = defaultdict(set)
for _ in range(N):
b, c = map(int, input().split())
b -= 1
freq[c].add(b)
uf = UnionFind(M)
for bs in map(list, freq.values()):
hd = bs[0]
for i in range(len(bs)):
uf.unite(hd, bs[i])
ans = 0
used = set()
for i in range(M):
r = uf.root(i)
if r in used: continue
used.add(r)
ans += uf.size(r) - 1
print(ans)
הההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההה
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
0