結果

問題 No.2563 色ごとのグループ
ユーザー neko_the_shadowneko_the_shadow
提出日時 2024-02-16 18:51:29
言語 Rust
(1.77.0)
結果
AC  
実行時間 133 ms / 2,000 ms
コード長 1,345 bytes
コンパイル時間 1,329 ms
コンパイル使用メモリ 195,780 KB
実行使用メモリ 34,176 KB
最終ジャッジ日時 2024-02-16 18:51:34
合計ジャッジ時間 4,413 ms
ジャッジサーバーID
(参考情報)
judge11 / judge14
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 1 ms
6,676 KB
testcase_01 AC 1 ms
6,676 KB
testcase_02 AC 1 ms
6,676 KB
testcase_03 AC 0 ms
6,676 KB
testcase_04 AC 1 ms
6,676 KB
testcase_05 AC 1 ms
6,676 KB
testcase_06 AC 0 ms
6,676 KB
testcase_07 AC 1 ms
6,676 KB
testcase_08 AC 1 ms
6,676 KB
testcase_09 AC 1 ms
6,676 KB
testcase_10 AC 1 ms
6,676 KB
testcase_11 AC 1 ms
6,676 KB
testcase_12 AC 1 ms
6,676 KB
testcase_13 AC 1 ms
6,676 KB
testcase_14 AC 2 ms
6,676 KB
testcase_15 AC 2 ms
6,676 KB
testcase_16 AC 2 ms
6,676 KB
testcase_17 AC 2 ms
6,676 KB
testcase_18 AC 2 ms
6,676 KB
testcase_19 AC 2 ms
6,676 KB
testcase_20 AC 7 ms
6,676 KB
testcase_21 AC 5 ms
6,676 KB
testcase_22 AC 3 ms
6,676 KB
testcase_23 AC 5 ms
6,676 KB
testcase_24 AC 46 ms
10,348 KB
testcase_25 AC 47 ms
10,552 KB
testcase_26 AC 62 ms
18,496 KB
testcase_27 AC 79 ms
34,032 KB
testcase_28 AC 69 ms
18,732 KB
testcase_29 AC 133 ms
34,172 KB
testcase_30 AC 107 ms
34,172 KB
testcase_31 AC 108 ms
34,176 KB
testcase_32 AC 105 ms
34,056 KB
testcase_33 AC 70 ms
6,676 KB
testcase_34 AC 72 ms
6,676 KB
testcase_35 AC 70 ms
6,676 KB
testcase_36 AC 68 ms
6,676 KB
testcase_37 AC 70 ms
6,676 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

use std::{collections::{HashMap, HashSet}, io::stdin};

fn main() {
    let nm = input();
    let n = nm[0];
    let m = nm[1];
    let c = input();

    let mut uf = UnionFind::new(n);
    for _ in 0..m {
        let uv = input();
        let u = uv[0] - 1;
        let v = uv[1] - 1;
        if c[u] == c[v] {
            uf.union(u, v);
        }
    }

    let mut map = HashMap::new();
    for i in 0..n {
        map.entry(c[i]).or_insert_with(|| HashSet::new()).insert(uf.find(i));
    }
    
    let ret = map.iter().map(|(_k, v)| v.len()-1).sum::<usize>();
    println!("{}", ret);
}

fn input() -> Vec<usize> {
    let mut buf = String::new();
    stdin().read_line(&mut buf).unwrap();
    buf.split_whitespace().map(|token| token.parse().unwrap()).collect::<Vec<usize>>()
}

pub struct UnionFind {
    parent: Vec<usize>
}

impl UnionFind {
    pub fn new(n: usize) -> Self {
        let parent = (0..n).collect::<Vec<_>>();
        UnionFind{ parent}
    }

    pub fn find(&mut self, x: usize) -> usize {
        if self.parent[x] == x {
            return x;
        }
        self.parent[x] = self.find(self.parent[x]);
        self.parent[x]
    }

    pub fn union(&mut self, x: usize, y: usize) {
        let x = self.find(x);
        let y = self.find(y);
        if x != y {
            self.parent[x] = y;
        }
    }
}
0