首页 > 其他 > 详细

并查集

时间:2018-09-14 22:05:46      阅读:132      评论:0      收藏:0      [点我收藏+]

代码1:

#include <bits/stdc++.h>
using namespace std;

const int maxn = 1e5 + 10;
int par[maxn];
int rank[maxn];

void init(int n) {
    for(int i = 0; i < n; i ++) {
        par[i] = i;
        rank[i] = 0;
    }
}

int find(int x) {
    if(par[x] == x)
        return x;
    else
        return par[x] = find(par[x]);
}

int unite(int x, int y) {
    x = find(x);
    y = find(y);
    if(x == y) return;

    if(rank[x] < rank[y])
        par[x] = y;
    else {
        par[y] = x;
        if(rank[x] == rank[y])
            rank[x] ++;
    }
}

bool same(int x, int y) {
    return find(x) == find(y);
}

  

代码2:

#include <bits/stdc++.h>
using namespace std;

int N;
int c;
int fa[20];

int dfs(int z) {
    if(fa[z] == z) return z;
    else
        return fa[z] = dfs(fa[z]);
}

int main() {
    scanf("%d", &N);
    for(int i = 1; i <= N; i ++)
        fa[i] = i;
    while(N --) {
        int x, y;
        scanf("%d", &c);
        scanf("%d%d", &x, &y);
        if(c == 0)
            fa[y] = dfs(x);
        else if(c == 1) {
            if(dfs(x) == dfs(y))
                printf("YES\n");
            else
                printf("NO\n");
        }
    }
    return 0;
}

  

并查集

原文:https://www.cnblogs.com/zlrrrr/p/9649095.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!