結果

問題 No.2563 色ごとのグループ
ユーザー navel_tosnavel_tos
提出日時 2023-12-02 15:48:51
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 370 ms / 2,000 ms
コード長 1,254 bytes
コンパイル時間 172 ms
コンパイル使用メモリ 81,700 KB
実行使用メモリ 110,864 KB
最終ジャッジ日時 2023-12-02 15:48:59
合計ジャッジ時間 7,383 ms
ジャッジサーバーID
(参考情報)
judge12 / judge14
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 37 ms
55,616 KB
testcase_01 AC 35 ms
55,616 KB
testcase_02 AC 37 ms
55,616 KB
testcase_03 AC 37 ms
55,616 KB
testcase_04 AC 37 ms
55,612 KB
testcase_05 AC 35 ms
55,616 KB
testcase_06 AC 35 ms
55,616 KB
testcase_07 AC 36 ms
55,616 KB
testcase_08 AC 36 ms
55,616 KB
testcase_09 AC 37 ms
55,616 KB
testcase_10 AC 40 ms
55,616 KB
testcase_11 AC 41 ms
55,616 KB
testcase_12 AC 38 ms
55,616 KB
testcase_13 AC 36 ms
55,616 KB
testcase_14 AC 73 ms
76,568 KB
testcase_15 AC 73 ms
76,568 KB
testcase_16 AC 76 ms
76,808 KB
testcase_17 AC 73 ms
76,824 KB
testcase_18 AC 54 ms
68,724 KB
testcase_19 AC 84 ms
76,568 KB
testcase_20 AC 85 ms
77,392 KB
testcase_21 AC 81 ms
76,760 KB
testcase_22 AC 81 ms
76,644 KB
testcase_23 AC 89 ms
76,772 KB
testcase_24 AC 180 ms
87,828 KB
testcase_25 AC 160 ms
89,304 KB
testcase_26 AC 188 ms
97,944 KB
testcase_27 AC 182 ms
108,412 KB
testcase_28 AC 258 ms
100,812 KB
testcase_29 AC 268 ms
110,860 KB
testcase_30 AC 265 ms
110,860 KB
testcase_31 AC 263 ms
110,864 KB
testcase_32 AC 287 ms
110,856 KB
testcase_33 AC 343 ms
109,176 KB
testcase_34 AC 329 ms
108,608 KB
testcase_35 AC 341 ms
108,608 KB
testcase_36 AC 370 ms
109,176 KB
testcase_37 AC 337 ms
109,176 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

#緑以下G

#UnionFind
class UnionFind:
    def __init__(self,N): self._parent=[-1 for i in[0]*N]
    def find(self,v):  #頂点vの親を探し、経路圧縮する
        vertices=[]
        while self._parent[v]>=0: vertices.append(v);v=self._parent[v]
        for i in vertices: self._parent[i]=v
        return v
    def unite(self,x,y):  #頂点xとyを併合し、併合の有無を返す
        x,y = self.find(x),self.find(y)
        if x==y: return 0
        if self._parent[x]>self._parent[y]: x,y=y,x  #負値で管理
        self._parent[x]+=self._parent[y]; self._parent[y]=x; return 1
    def same(self,x,y):return self.find(x)==self.find(y)   #xとyは同一集合か返す
    def size(self,x):  return -self._parent[self.find(x)]  #xの集合のサイズを求める


from collections import defaultdict

#入力受取
N,M = map(int,input().split())
C = list(map(int,input().split()))
UF = UnionFind(N)
for _ in range(M):
    u,v = map(lambda x: int(x)-1,input().split())
    if C[u] == C[v]: UF.unite(u,v)

#色ごとに連結判定
D = defaultdict(list)
for i,c in enumerate(C): D[c].append(i)
ans = 0
for c in D.keys():
    base = D[c][0]
    for i in D[c]:
        if not UF.same(base,i): UF.unite(base,i); ans += 1
print(ans)
0