一个并查集对象

实现并查集的查找、合并、类别size

 class UF{
     constructor(n){
         this.parent=Array(n)
         this.size=[]
         for (let i = 0; i < n; i++) {
            this.parent[i] = i;
            this.size[i] = 1;
        }
     }
     find(x){
        const parent=this.parent;
        if (parent[x] != x) {
            parent[x] = this.find(parent[x]);
        }
        return parent[x];
     }
     merge(x,y){
        x=this.find(x)
        y=this.find(y)
        if (x == y) return;
        this.parent[y] = x;
        // 注意 别写反了
        this.size[x] += this.size[y];
     }
 }

  

posted @ 2022-12-14 20:38  巅峰蜗牛  阅读(12)  评论(0编辑  收藏  举报