Skip to content

Instantly share code, notes, and snippets.

@YoshiTheChinchilla
Created September 7, 2020 12:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save YoshiTheChinchilla/9beafb56dee11fb66bf57ff5316260f2 to your computer and use it in GitHub Desktop.
Save YoshiTheChinchilla/9beafb56dee11fb66bf57ff5316260f2 to your computer and use it in GitHub Desktop.
The simplest Union-find written in Rust. Edit this code with your taste and use it.
struct UnionFind {
par: Vec<usize>,
rank: Vec<usize>,
}
impl UnionFind {
fn new(n: usize) -> UnionFind {
let mut par = Vec::with_capacity(n);
for i in 0..n {
par[i] = i;
}
UnionFind {
par,
rank: vec![0;n],
}
}
fn find(&mut self, x: usize) -> usize {
if x == self.par[x] {
x
} else {
self.par[x] = self.find(self.par[x]);
self.par[x]
}
}
fn unite(&mut self, x: usize, y: usize) {
let x = self.find(x);
let y = self.find(y);
if self.rank[x] > self.rank[y] {
self.par[y] = x;
} else {
self.par[x] = y;
if self.rank[x] == self.rank[y] {
self.rank[y] += 1;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment