Cod sursa(job #2861468)

Utilizator redstonegamer22Andrei Ion redstonegamer22 Data 4 martie 2022 00:20:49
Problema Paduri de multimi disjuncte Scor 30
Compilator rs Status done
Runda Arhiva educationala Marime 1.78 kb
use std::io::*;
use std::fs::File;

fn main() {
    let mut infile = BufReader::new(File::open("disjoint.in").unwrap());
    let mut outfile = BufWriter::new(File::create("disjoint.out").unwrap());

    let (n, m) = {
        let mut line = String::new();
        infile.read_line(&mut line).unwrap();
        let vec : Vec<u32> = line.trim().split(' ').map(|x| x.parse().unwrap()).collect();
        (vec[0], vec[1])
    };

    dbg!(n, m);

    let mut fathers : Vec<u32> = (0..n as u32).collect();
    dbg!(&fathers);

    let mut sizes : Vec<u32> = vec![1_u32; n as usize];
    dbg!(&sizes);

    fn get_father(x : u32, fathers : &mut Vec<u32>) -> u32 {
        if fathers[x as usize] == x { x } else { fathers[x as usize] = get_father(fathers[x as usize], fathers); fathers[x as usize] }
    }

    for _query in 0..m {
        let (t, mut x, mut y) = {
            let mut line = String::new();
            infile.read_line(&mut line).unwrap();
            let vec : Vec<u32> = line.trim().split(' ').map(|x| x.parse().unwrap()).collect();
            (vec[0], vec[1] - 1, vec[2] - 1)
        };
        dbg!(t, x, y);

        match t {
            1 => {
                x = get_father(x, &mut fathers);
                y = get_father(y, &mut fathers);

                if sizes[x as usize] > sizes[y as usize] { std::mem::swap(&mut x, &mut y); }

                // Join trees
                fathers[x as usize] = y;
                sizes[y as usize] += fathers[x as usize];
            },
            2 => {
                x = get_father(x, &mut fathers);
                y = get_father(y, &mut fathers);

                writeln!(outfile, "{}", if x == y { "DA" } else { "NU" }).unwrap();
            }
            _ => {
                panic!("This should not be reachable");
            }
        }
    }
}