結果
問題 | No.2563 色ごとのグループ |
ユーザー |
![]() |
提出日時 | 2023-12-02 15:34:00 |
言語 | PyPy3 (7.3.15) |
結果 |
AC
|
実行時間 | 355 ms / 2,000 ms |
コード長 | 1,809 bytes |
コンパイル時間 | 195 ms |
コンパイル使用メモリ | 82,520 KB |
実行使用メモリ | 111,488 KB |
最終ジャッジ日時 | 2024-09-26 18:54:22 |
合計ジャッジ時間 | 6,131 ms |
ジャッジサーバーID (参考情報) |
judge3 / judge2 |
(要ログイン)
ファイルパターン | 結果 |
---|---|
sample | AC * 3 |
other | AC * 35 |
ソースコード
"""考察色違いの場合、辺はないと考えて良さそう色ごとのグループ数 - 1 の和が答え色ごとの頂点数を数えておく辺を結ぶたびに、その色の頂点数を1減らす"""# from my.union_find import UnionFindclass UnionFind:def __init__(self, n: int) -> None:self.parents = [-1] * nself.data = [0] * nself.n = ndef root(self, x: int) -> int:if self.parents[x] < 0:return xself.parents[x] = self.root(self.parents[x])return self.parents[x]def unite(self, x: int, y: int) -> None:x = self.root(x)y = self.root(y)if x == y:returnif self.parents[x] > self.parents[y]:x, y = y, xself.parents[x] += self.parents[y]self.parents[y] = xdef size(self, x: int) -> int:return -self.parents[self.root(x)]def roots(self) -> list[int]:return [i for i, x in enumerate(self.parents) if x < 0]def same(self, x, y) -> bool:return self.root(x) == self.root(y)def groups(self) -> dict[int, list[int]]:group_members = {}for member in range(self.n):p = self.root(member)if not p in group_members:group_members[p] = []group_members[p].append(member)return group_membersN, M = map(int, input().split())C = list(map(lambda x:int(x)-1, input().split()))cnt = [0] * Nfor c in C:cnt[c] += 1uf = UnionFind(N)for _ in range(M):a, b = map(int, input().split())a -= 1; b -= 1if C[a] == C[b]:if uf.same(a, b):continueelse:uf.unite(a, b)cnt[C[a]] -= 1ans = sum(c - 1 for c in cnt if c > 0)print(ans)