結果

問題 No.2563 色ごとのグループ
ユーザー Theta
提出日時 2023-12-15 15:41:26
言語 Python3
(3.13.1 + numpy 2.2.1 + scipy 1.14.1)
結果
AC  
実行時間 1,863 ms / 2,000 ms
コード長 2,251 bytes
コンパイル時間 259 ms
コンパイル使用メモリ 12,800 KB
実行使用メモリ 125,328 KB
最終ジャッジ日時 2024-09-27 06:26:53
合計ジャッジ時間 23,959 ms
ジャッジサーバーID
(参考情報)
judge1 / judge3
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 3
other AC * 35
権限があれば一括ダウンロードができます

ソースコード

diff #

from collections import defaultdict
import sys
sys.setrecursionlimit(20000)


class UnionFindTree:
    def __init__(self, length: int) -> None:
        self.list = [idx for idx in range(length)]
        self.size = [1 for _ in range(length)]

    def get_root(self, idx: int) -> int:
        if self.list[idx] == idx:
            return idx
        self.list[idx] = self.get_root(self.list[idx])
        return self.list[idx]

    def is_same(self, idx1: int, idx2: int) -> bool:
        return self.get_root(idx1) == self.get_root(idx2)

    def merge(self, idx1: int, idx2: int):
        if self.is_same(idx1, idx2):
            return

        idx1_root = self.get_root(idx1)
        idx2_root = self.get_root(idx2)
        if self.size[idx1_root] > self.size[idx2_root]:
            self.list[idx2_root] = idx1_root
            self.size[idx1_root] += self.size[idx2_root]
        else:
            self.list[idx1_root] = idx2_root
            self.size[idx2_root] += self.size[idx1_root]

    def get_size(self, idx: int) -> int:
        return self.size[self.get_root(idx)]


def main():
    N, M = map(int, input().split())
    C = list(map(int, input().split()))
    graph: list[set[int]] = [set() for _ in range(N)]
    for _ in range(M):
        dep, dest = map(lambda n: int(n) - 1, input().split())
        graph[dep].add(dest)
        graph[dest].add(dep)

    color_node: dict[int, set[int]] = defaultdict(set)
    for node_idx, color in enumerate(C):
        color_node[color].add(node_idx)

    add_edge_ctr = 0
    for current_color, nodes in color_node.items():
        node_comp = {node_idx: idx for idx, node_idx in enumerate(nodes)}
        uft = UnionFindTree(len(nodes))
        for node_idx, comp_idx in node_comp.items():
            for neighbor_node_idx in graph[node_idx]:
                if neighbor_node_idx not in nodes:
                    continue
                uft.merge(comp_idx, node_comp[neighbor_node_idx])

        for node_idx, comp_idx in node_comp.items():
            if comp_idx == 0:
                continue
            if uft.is_same(comp_idx, 0):
                continue
            uft.merge(comp_idx, 0)
            add_edge_ctr += 1
    print(add_edge_ctr)


if __name__ == "__main__":
    main()
0