結果
問題 | 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,dequefrom itertools import combinations,permutations,accumulate,productfrom bisect import bisect,bisect_left,bisect_rightfrom heapq import heappop,heappush,heapify#from sortedcontainers import SortedList,SortedSetdef 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, xself.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 = 0gro = 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): continueuf.union(u,v)cnt[C[u-1]] += 1for c in gro.keys():ans += max(len(gro[c])-cnt[c]-1,0)print(ans)