結果

問題 No.1054 Union add query
ユーザー uw_yu1rabbituw_yu1rabbit
提出日時 2021-03-13 02:30:56
言語 Rust
(1.77.0)
結果
RE  
実行時間 -
コード長 1,549 bytes
コンパイル時間 1,489 ms
コンパイル使用メモリ 170,296 KB
実行使用メモリ 7,808 KB
最終ジャッジ日時 2024-04-22 16:10:31
合計ジャッジ時間 3,594 ms
ジャッジサーバーID
(参考情報)
judge1 / judge4
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 1 ms
5,248 KB
testcase_01 AC 1 ms
5,376 KB
testcase_02 AC 1 ms
5,376 KB
testcase_03 RE -
testcase_04 RE -
testcase_05 RE -
testcase_06 RE -
testcase_07 RE -
testcase_08 RE -
testcase_09 RE -
testcase_10 AC 92 ms
7,808 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

#[allow(dead_code)]
#[allow(unused_imports)]
fn read<T: std::str::FromStr>() -> T {
    use std::io::*;
    let stdin = stdin();
    let stdin = stdin.lock();
    let token: String = stdin
        .bytes()
        .map(|c| c.expect("failed to read char") as char)
        .skip_while(|c| c.is_whitespace())
        .take_while(|c| !c.is_whitespace())
        .collect();
    token.parse().ok().expect("failed to parse token")
}

fn root (par:&Vec<usize>, mut x:usize) -> usize {
    while par[x] != x {
        x = par[x];
    }
    x
}
fn main(){
    let n:usize = read();
    let query:usize = read();
    let mut par:Vec<usize> = (0..n).collect();
    let mut sum = vec![0i64;n];
    let mut sz = vec![1;n];
    for _ in 0..query {
        let t:usize = read();
        let mut a:usize = read();
        let mut b:usize = read();
        if t == 1 {
            a -= 1;
            b -= 1;
            a = root(&par,a);
            b = root(&par,b);
            if a != b {
                if sz[a] < sz[b] {
                    std::mem::swap(&mut a,&mut b);
                }
                sz[a] += sz[b];
                sum[b] -= sum[a];
                par[b] = a;
            }
        }else if t == 2 {
            a -= 1;
            a = root(&par,a);
            sum[a] += b as i64;
        }else {
            a -= 1;
            let mut x = a;
            let mut ans = sum[x];
            while x != par[x] {
                x = par[x];
                ans += sum[x];
            }
            println!("{}",ans);
        }
    }
}
0