Created
September 7, 2020 12:06
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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