题解 | 【模板】并查集

【模板】并查集

https://www.nowcoder.com/practice/513111e4477c4fad8f19f14d4cdf49dc

const rl = require("readline").createInterface({ input: process.stdin });
var iter = rl[Symbol.asyncIterator]();
const readline = async () => (await iter.next()).value;
const get = async () => (await readline()).split(" ");
void async function () {
    const [n,q] = (await get()).map(Number);
    const uf = new UF(n + 1);
    for (let k = 0 ; k < q ; k++){
        const arr = (await get()).map(Number);
        const op = arr[0];
        if (op === 1){
            uf.union(arr[1],arr[2]);
        }else if (op === 2){
            const x = uf.find(arr[1]);
            const y = uf.find(arr[2]);
            if (x !== y) console.log('NO');
            else console.log('YES');
        }else{
            console.log(uf.size[uf.find(arr[1])]);
        }
    }

}()
class UF{
    constructor(n){
        this.n = n;
        this.p = Array(n).fill(0);
        this.size = Array(n).fill(1);
        for (let i = 0 ; i < n ; i++){
            this.p[i] = i;
        }
    }

    union(a,b){
        const fa = this.find(a);
        const fb = this.find(b);
        if (fa !== fb){
            this.p[fa] = fb;
            this.size[fb] += this.size[fa];
        }
    }

    find(a){
       if (this.p[a] !== a) this.p[a] = this.find(this.p[a]);
       return this.p[a];
    }
}

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务