Skip to content

Instantly share code, notes, and snippets.

@nak3
Last active December 10, 2017 12:37
Show Gist options
  • Save nak3/9ad235e229cafd5866697625eb4d1d63 to your computer and use it in GitHub Desktop.
Save nak3/9ad235e229cafd5866697625eb4d1d63 to your computer and use it in GitHub Desktop.
use std::io::*;
use std::str::*;
//const MOD: i32 = 1000000007;
// fn read<T: FromStr>() -> Option<T> {
// let stdin = stdin();
// let s = stdin
// .bytes()
// .map(|c| c.unwrap() as char)
// .take_while(|c| !c.is_whitespace())
// .collect::<String>();
// s.parse::<T>().ok()
// }
struct UF {
d: Vec<i64>,
}
impl UF {
fn new(n: i64) -> UF {
let mut d: Vec<i64> = Vec::new();
for _ in 0..n {
d.push(-1);
}
return UF { d: d };
}
fn root(&mut self, vv: usize) -> i64 {
let v = vv as usize;
if self.d[v as usize] < 0 {
return v as i64;
}
let tmp = self.d[v] as usize;
self.d[v] = self.root(tmp);
return self.d[v];
}
fn unite(&mut self, x: usize, y: usize) -> bool {
let mut xx = self.root(x) as usize;
let mut yy = self.root(y) as usize;
if xx == yy {
return false;
}
let tmpx = self.size(xx);
let tmpy = self.size(yy);
if tmpx < tmpy {
let tmp = xx;
xx = yy;
yy = tmp;
}
self.d[xx] += self.d[yy];
self.d[yy] = xx as i64;
return true;
}
fn size(&mut self, v: usize) -> i64 {
let tmp = self.root(v) as usize;
return -1 * self.d[tmp] as i64;
}
}
fn main() {
// let n: usize = read().unwrap();
let mut uf = UF::new(1000);
uf.unite(1, 2);
uf.unite(0, 1);
println!("{}", uf.size(2));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment