結果
| 問題 | No.2563 色ごとのグループ |
| コンテスト | |
| ユーザー |
|
| 提出日時 | 2023-12-02 15:17:27 |
| 言語 | PyPy3 (7.3.15) |
| 結果 |
AC
|
| 実行時間 | 538 ms / 2,000 ms |
| コード長 | 2,311 bytes |
| 記録 | |
| コンパイル時間 | 301 ms |
| コンパイル使用メモリ | 82,368 KB |
| 実行使用メモリ | 178,016 KB |
| 最終ジャッジ日時 | 2024-09-26 18:23:16 |
| 合計ジャッジ時間 | 9,854 ms |
|
ジャッジサーバーID (参考情報) |
judge3 / judge4 |
(要ログイン)
| ファイルパターン | 結果 |
|---|---|
| sample | AC * 3 |
| other | AC * 35 |
ソースコード
from collections import defaultdict
from collections import defaultdict
class UnionFind():
def __init__(self, n):
self.n = n
self.parents = [-1] * n
def find(self, x):
assert 0 <= x
if self.parents[x] < 0:
return x
else:
self.parents[x] = self.find(self.parents[x])
return self.parents[x]
def unite(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
def __str__(self):
return '\n'.join(f'{r}: {m}' for r, m in self.all_group_members().items())
N, M = map(int, input().split())
C = list(map(int, input().split()))
u = []
v = []
for i in range(M):
ui, vi = map(int, input().split())
ui -= 1
vi -= 1
u.append(ui)
v.append(vi)
Ccount = defaultdict(int)
ColorV = [[] for _ in range(N)]
for i in range(N):
C[i] -= 1
Ccount[C[i]] += 1
ColorV[C[i]].append(i)
ColorUFdict: "dict[int, UnionFind]" = {}
v2i = defaultdict(int)
# i: color
for i in range(N):
if Ccount[i] == 0:
continue
uf = UnionFind(Ccount[i])
ColorUFdict[i] = uf
for j in range(len(ColorV[i])):
v2i[ColorV[i][j]] = j
for i in range(M):
if C[u[i]] == C[v[i]]:
ColorUFdict[C[u[i]]].unite(v2i[u[i]], v2i[v[i]])
ans = 0
for i in range(N):
if Ccount[i] == 0:
continue
fr = v2i[ColorV[i][0]]
uf = ColorUFdict[i]
for x in ColorV[i]:
to = v2i[x]
if not uf.same(fr, to):
ans += 1
uf.unite(fr, to)
print(ans)