Make great things

What I cannot create, I do not understand.

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

最近在刷 Leetcode, 每日题打卡题经常出现并查集, 这里记录下使用 Rust 实现的并查集.

    pub struct UnionFind {
        n: usize,
        fa: Vec<usize>,
    }

    impl UnionFind {
        pub fn new(n: usize) -> Self {
            Self {
                n,
                fa: (0..n).collect(),
            }
        }

        // 并查集中不同集合的数量
        pub fn count(&self) -> usize {
            let mut c = 0;
            for i in 0..self.fa.len() {
                if self.fa[i] == i {
                    c += 1;
                }
            }
            c
        }

        pub fn find(&mut self, x: usize) -> usize {
            assert_eq!(x < self.n, true);
            if self.fa[x] == x {
                x
            } else {
                // 路径压缩
                let find_fa = self.find(self.fa[x]);
                self.fa[x] = find_fa;
                self.fa[x]
            }
        }

        pub fn merge(&mut self, i: usize, j: usize) {
            let ifa = self.find(i);
            let jfa = self.find(j);
            self.fa[ifa] = jfa;
        }

        pub fn connected(&mut self, i: usize, j: usize) -> bool {
            self.find(i) == self.find(j)
        }
    }
posted on 2021-01-28 22:00  wbin91  阅读(193)  评论(0编辑  收藏  举报