結果

問題 No.1390 Get together
ユーザー tonyu0
提出日時 2021-02-12 22:45:34
言語 Rust
(1.83.0 + proconio)
結果
AC  
実行時間 72 ms / 2,000 ms
コード長 2,077 bytes
コンパイル時間 15,233 ms
コンパイル使用メモリ 379,824 KB
実行使用メモリ 18,304 KB
最終ジャッジ日時 2024-07-19 23:41:57
合計ジャッジ時間 18,204 ms
ジャッジサーバーID
(参考情報)
judge5 / judge1
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 3
other AC * 29
権限があれば一括ダウンロードができます

ソースコード

diff #

use std::io::*;

mod disjoint_set {
    pub struct DisjointSet {
        parent: Vec<usize>,
        size: Vec<usize>,
    }
    impl DisjointSet {
        pub fn new(n: usize) -> DisjointSet {
            DisjointSet {
                parent: (0..n).collect(),
                size: vec![1; n],
            }
        }
        fn root(&mut self, x: usize) -> usize {
            if x == self.parent[x] {
                x
            } else {
                let tmp = self.parent[x];
                self.parent[x] = self.root(tmp);
                self.parent[x]
            }
        }
        pub fn merge(&mut self, x: usize, y: usize) {
            let x = self.root(x);
            let y = self.root(y);
            if x == y {
                return;
            }
            if self.size[x] > self.size[y] {
                self.size[x] += self.size[y];
                self.parent[y] = x;
            } else {
                self.size[y] += self.size[x];
                self.parent[x] = y;
            }
        }
        pub fn same(&mut self, x: usize, y: usize) -> bool {
            self.root(x) == self.root(y)
        }
    }
}

fn main() {
    let mut s: String = String::new();
    std::io::stdin().read_to_string(&mut s).ok();
    let mut itr = s.trim().split_whitespace();
    let n: usize = itr.next().unwrap().parse().unwrap();
    let m: usize = itr.next().unwrap().parse().unwrap();
    let mut col: Vec<Vec<usize>> = vec![vec![]; n];
    for _ in 0..n {
        let b = itr.next().unwrap().parse::<usize>().unwrap() - 1;
        let c = itr.next().unwrap().parse::<usize>().unwrap() - 1;
        col[c].push(b);
    }

    let mut ds = disjoint_set::DisjointSet::new(m);
    let mut ans = 0;
    for i in 0..n {
        if col[i].len() <= 1 {
            continue;
        }
        col[i].sort();
        col[i].dedup();
        for j in 0..col[i].len() - 1 {
            if !ds.same(col[i][j], col[i][j + 1]) {
                ds.merge(col[i][j], col[i][j + 1]);
                ans += 1;
            }
        }
    }
    println!("{}", ans);
}
0