結果

問題 No.2563 色ごとのグループ
ユーザー n_nan_na
提出日時 2024-01-04 10:37:40
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 486 ms / 2,000 ms
コード長 1,493 bytes
コンパイル時間 304 ms
コンパイル使用メモリ 81,572 KB
実行使用メモリ 110,224 KB
最終ジャッジ日時 2024-01-04 10:37:50
合計ジャッジ時間 9,680 ms
ジャッジサーバーID
(参考情報)
judge14 / judge13
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 35 ms
53,460 KB
testcase_01 AC 37 ms
53,460 KB
testcase_02 AC 36 ms
53,460 KB
testcase_03 AC 36 ms
53,460 KB
testcase_04 AC 36 ms
53,460 KB
testcase_05 AC 35 ms
53,460 KB
testcase_06 AC 36 ms
53,460 KB
testcase_07 AC 35 ms
53,460 KB
testcase_08 AC 35 ms
53,460 KB
testcase_09 AC 37 ms
53,460 KB
testcase_10 AC 35 ms
53,460 KB
testcase_11 AC 38 ms
53,460 KB
testcase_12 AC 36 ms
53,460 KB
testcase_13 AC 37 ms
53,460 KB
testcase_14 AC 68 ms
70,920 KB
testcase_15 AC 67 ms
70,916 KB
testcase_16 AC 66 ms
70,916 KB
testcase_17 AC 66 ms
70,920 KB
testcase_18 AC 49 ms
64,332 KB
testcase_19 AC 71 ms
74,484 KB
testcase_20 AC 81 ms
76,696 KB
testcase_21 AC 77 ms
76,404 KB
testcase_22 AC 76 ms
76,532 KB
testcase_23 AC 83 ms
76,276 KB
testcase_24 AC 193 ms
87,920 KB
testcase_25 AC 164 ms
89,868 KB
testcase_26 AC 228 ms
99,352 KB
testcase_27 AC 269 ms
109,584 KB
testcase_28 AC 253 ms
102,340 KB
testcase_29 AC 333 ms
110,028 KB
testcase_30 AC 319 ms
110,028 KB
testcase_31 AC 354 ms
110,028 KB
testcase_32 AC 320 ms
109,900 KB
testcase_33 AC 448 ms
110,224 KB
testcase_34 AC 458 ms
109,636 KB
testcase_35 AC 449 ms
109,636 KB
testcase_36 AC 452 ms
110,224 KB
testcase_37 AC 486 ms
110,224 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

class UnionFind:
    
    def __init__(self, n):
        self.par = [-1]*n # 要素の根(親)
        self.rank = [0]*n # 要素が属している木の高さ
        self.siz = [1]*n # 要素が属している木の大きさ(要素数)

    # xのroot(Find)
    def root(self, x):
        if self.par[x] == -1:
            return x
        else:
            self.par[x] = self.root(self.par[x])
            return self.par[x]
    
    # xとyをmerge(Union)
    def merge(self, x, y):
        rx,ry = self.root(x), self.root(y)
        if rx == ry: return False
        if self.rank[rx] < self.rank[ry]:
            rx,ry = ry,rx # rx: 親, ry: 子
        self.par[ry] = rx
        if self.rank[rx] == self.rank[ry]:
            self.rank[rx] += 1        
        self.siz[rx] += self.siz[ry]
        return True
            
    # xとyが同一のgroupかどうか
    def issame(self, x, y):
        return self.root(x) == self.root(y)
    
    # xが含まれる木のサイズ
    def size(self, x):
        return self.siz[self.root(x)]

#---------------------------------------------------
N,M = map(int,input().split())
uf = UnionFind(N)

C = list(map(int,input().split()))

for _ in range(M):
    u,v = map(int,input().split())
    if C[u-1] != C[v-1]: continue
    uf.merge(u-1, v-1)
    
par = [set() for _ in range(N)]
for i in range(N):
    idx = uf.root(i)
    par[C[i] - 1].add(idx)

ans = 0
for p in par:
    if not p: continue
    ans += len(p) - 1
    
print(ans)
0