結果
| 問題 |
No.2563 色ごとのグループ
|
| コンテスト | |
| ユーザー |
かもめのうで
|
| 提出日時 | 2023-12-02 19:57:02 |
| 言語 | PyPy3 (7.3.15) |
| 結果 |
AC
|
| 実行時間 | 498 ms / 2,000 ms |
| コード長 | 2,180 bytes |
| コンパイル時間 | 261 ms |
| コンパイル使用メモリ | 82,176 KB |
| 実行使用メモリ | 112,512 KB |
| 最終ジャッジ日時 | 2024-09-26 21:34:46 |
| 合計ジャッジ時間 | 8,402 ms |
|
ジャッジサーバーID (参考情報) |
judge2 / judge1 |
(要ログイン)
| ファイルパターン | 結果 |
|---|---|
| sample | AC * 3 |
| other | AC * 35 |
ソースコード
from collections import defaultdict
class UnionFind():
def __init__(self, n):
self.par = [-1]*n#頂点xの親を記録
self.rank = [0]*n#頂点xが属する根付き木の高さを記録
self.siz = [1]*n#その頂点数を記録
self.edgecount = [0]*n#頂点xの親の属する根付き木の辺の数
#xの根を求める
def root(self, x):
# while True:
# if self.par[x] == -1:
# break
# x = self.par[x]
# return x
#経路圧縮
if self.par[x] == -1:
return x
else:
self.par[x] = self.root(self.par[x])
return self.par[x]
#xとyの統合
def unite(self, x, y):
rx = self.root(x)
ry = self.root(y)
if rx == ry:
self.edgecount[rx] += 1
return False
#union by size
if self.siz[rx] < self.siz[ry]:
self.par[rx] = ry
self.siz[ry] += self.siz[rx]
self.edgecount[ry] += 1 + self.edgecount[rx]
else:
self.par[ry] = rx
self.siz[rx] += self.siz[ry]
self.edgecount[rx] += 1 + self.edgecount[ry]
return True
#xとyが同じグループに属すか
def issame(self, x, y):
if self.root(x) == self.root(y):
return True
return False
#xが属すグループの要素数を返す
def size(self, x):
return self.siz[self.root(x)]
#頂点xの親の属する根付き木の辺の数を返す
def edge(self, x):
return self.edgecount[self.root(x)]
#連結成分の個数を返す
def groupcount(self, x):
dic = defaultdict(int)
for i in range(x):
dic[self.root(i)] += 1
return len(dic)
n, m = map(int, input().split())
c = list(map(int, input().split()))
uf = UnionFind(n)
for _ in range(m):
v, u = map(int, input().split())
v -= 1
u -= 1
if c[v] == c[u]:
uf.unite(v, u)
d = defaultdict(int)
for i in range(n):
if i == uf.root(i):
d[c[i]] += 1
ans = 0
for i, j in d.items():
ans += j-1
print(ans)
かもめのうで