并查集

来源:互联网 发布:交易平台软件 编辑:程序博客网 时间:2024/05/29 13:02
#include <bits/stdc++.h>
int fa[2000];
// 还记得之前阅读课里讲的并查集算法
// father函数返回的是节点x的祖先节点
int father(int x) {
    if (fa[x] != x) fa[x] = father(fa[x]);
    return fa[x];
}
// 合并两个节点所在集合,同时判断两个点之前是否在一个集合里
// 函数返回true则之前两个点不在一个集合中
bool join(int x, int y) {
    int fx = father(x), fy = father(y);
    if (fx != fy) {
        fa[fx] = fy;
        return true;
    } else {
        return false;
    }
}
// 初始化一个n个点的并查集
void init(int n) {
    for (int i = 1; i <= n; ++i) fa[i] = i;
}




int main(){
    //第一行两个整数,表示句子数量n(1<=n<=1000),表示人数m(1<=m<=1000)
    int n, m, result = 0;
    scanf("%d%d", &n, &m);
    
    init(n);
    int 
    while(n--){
        int x, y;
        scanf("%d%d", &x, &y);
        if(join(x, y)){
            result++;
        }
    }
    
    printf("%d\n", result);
    return 0;
}
0 0
原创粉丝点击