結果
| 問題 |
No.1390 Get together
|
| コンテスト | |
| ユーザー |
|
| 提出日時 | 2021-02-13 01:55:33 |
| 言語 | PyPy3 (7.3.15) |
| 結果 |
AC
|
| 実行時間 | 465 ms / 2,000 ms |
| コード長 | 1,368 bytes |
| コンパイル時間 | 375 ms |
| コンパイル使用メモリ | 82,072 KB |
| 実行使用メモリ | 118,436 KB |
| 最終ジャッジ日時 | 2024-07-20 03:19:29 |
| 合計ジャッジ時間 | 9,376 ms |
|
ジャッジサーバーID (参考情報) |
judge2 / judge3 |
(要ログイン)
| ファイルパターン | 結果 |
|---|---|
| sample | AC * 3 |
| other | AC * 29 |
ソースコード
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 same(self, x, y):
return self.find(x) == self.find(y)
def roots(self):
return [i for i, x in enumerate(self.parents) if x < 0]
def members(self, x):
root = self.find(x)
return [i for i in range(self.n) if self.find(i) == root]
def size(self,x):
return abs(self.parents[self.find(x)])
def groups(self):
roots = self.roots()
r_to_g = {}
for i, r in enumerate(roots):
r_to_g[r] = i
groups = [[] for _ in roots]
for i in range(self.n):
groups[r_to_g[self.find(i)]].append(i)
return groups
N, M = map(int, input().split())
setlis = [set() for _ in range(N)]
for i in range(N):
b,c = map(int, input().split())
setlis[c-1].add(b-1)
uf = UnionFind(M)
ans = 0
for i in range(N):
lis = list(setlis[i])
if not len(lis): continue
a = lis[0]
for l in lis[1:]:
if not uf.same(a,l):
ans += 1
uf.union(a,l)
print(ans)