結果
| 問題 |
No.2563 色ごとのグループ
|
| コンテスト | |
| ユーザー |
|
| 提出日時 | 2023-12-02 15:17:00 |
| 言語 | PyPy3 (7.3.15) |
| 結果 |
AC
|
| 実行時間 | 384 ms / 2,000 ms |
| コード長 | 2,866 bytes |
| コンパイル時間 | 183 ms |
| コンパイル使用メモリ | 82,048 KB |
| 実行使用メモリ | 116,736 KB |
| 最終ジャッジ日時 | 2024-09-26 18:22:39 |
| 合計ジャッジ時間 | 7,620 ms |
|
ジャッジサーバーID (参考情報) |
judge1 / judge4 |
(要ログイン)
| ファイルパターン | 結果 |
|---|---|
| sample | AC * 3 |
| other | AC * 35 |
ソースコード
import sys,math
#if len(sys.argv)==2:sys.stdin=open(sys.argv[1])
from collections import defaultdict,deque
from itertools import combinations,permutations,accumulate,product
from bisect import bisect,bisect_left,bisect_right
from heapq import heappop,heappush,heapify
#from sortedcontainers import SortedList,SortedSet
def input(): return sys.stdin.readline().rstrip()
def ii(): return int(input())
def ms(): return map(int, input().split())
def li(): return list(map(int,input().split()))
class UnionFind(): # n頂点のUnion-Find木を作成
def __init__(self, n):
self.n = n
#各頂点の親(1個上の要素)を記入
self.parents = [-1] * (n+1) # その頂点が根なら-1(unionを実行すると-1以下の値になることもある)
# 頂点xの根を返す関数(経路圧縮)
def root(self, x):
if self.parents[x] < 0: return x # xが根ならxを返す
else:
self.parents[x] = self.root(self.parents[x])
return self.parents[x]
# 要素x,yを統合する関数
def union(self, x, y):
x = self.root(x)
y = self.root(y)
# x,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
# 要素xが属するグループの要素数を返す
def size(self, x): return -self.parents[self.root(x)]
# x,yが同じグループか(連結か)を返す関数
def same(self, x, y): return self.root(x) == self.root(y)
# xが属するグループの要素をリストで返す
def members(self, x):
root = self.root(x)
return [i for i in range(self.n) if self.root(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 = ms()
uf = UnionFind(N)
C = li()
ans = 0
gro = defaultdict(list)
for i in range(N):
gro[C[i]].append(i+1)
cnt = defaultdict(int)
for _ in range(M):
u,v = ms()
if C[u-1]==C[v-1]:
if uf.same(u,v): continue
uf.union(u,v)
cnt[C[u-1]] += 1
for c in gro.keys():
ans += max(len(gro[c])-cnt[c]-1,0)
print(ans)