結果
| 問題 |
No.2563 色ごとのグループ
|
| コンテスト | |
| ユーザー |
|
| 提出日時 | 2024-04-09 23:19:42 |
| 言語 | PyPy3 (7.3.15) |
| 結果 |
AC
|
| 実行時間 | 474 ms / 2,000 ms |
| コード長 | 1,246 bytes |
| コンパイル時間 | 325 ms |
| コンパイル使用メモリ | 82,304 KB |
| 実行使用メモリ | 122,624 KB |
| 最終ジャッジ日時 | 2024-10-01 23:58:27 |
| 合計ジャッジ時間 | 9,534 ms |
|
ジャッジサーバーID (参考情報) |
judge1 / judge5 |
(要ログイン)
| ファイルパターン | 結果 |
|---|---|
| sample | AC * 3 |
| other | AC * 35 |
ソースコード
from collections import defaultdict
class UnionFind():
def __init__(self, n):
self.n = n
self.root = [-1] * n
self.rank = [0] * n
def find(self, x):
if self.root[x] < 0:
return x
else:
self.root[x] = self.find(self.root[x])
return self.root[x]
def unite(self, x, y):
x = self.find(x)
y = self.find(y)
if x == y:
return
elif self.rank[x] > self.rank[y]:
self.root[x] += self.root[y]
self.root[y] = x
else:
self.root[y] += self.root[x]
self.root[x] = y
if self.rank[x] == self.rank[y]:
self.rank[y] += 1
def same(self, x, y):
return self.find(x) == self.find(y)
n, m = map(int, input().split())
cl = list(map(int, input().split()))
d = defaultdict(list)
for i, c in enumerate(cl):
d[c].append(i)
uf = UnionFind(n)
for _ in range(m):
u, v = map(int, input().split())
u, v = u - 1, v - 1
if cl[u] == cl[v]:
uf.unite(u, v)
ans = 0
for k in d.keys():
l = d[k]
for a, b in zip(l, l[1:]):
if uf.same(a, b):
continue
uf.unite(a, b)
ans += 1
print(ans)