九度OJ 朋友圈 -- 并查集

题目地址:http://ac.jobdu.com/problem.php?pid=1526

题目描述:

假如已知有n个人和m对好友关系(存于数字r)。如果两个人是直接或间接的好友(好友的好友的好友...),则认为他们属于同一个朋友圈,请写程序求出这n个人里一共有多少个朋友圈。
假如:n = 5 , m = 3 , r = {{1 , 2} , {2 , 3} , {4 , 5}},表示有5个人,1和2是好友,2和3是好友,4和5是好友,则1、2、3属于一个朋友圈,4、5属于另一个朋友圈,结果为2个朋友圈。

输入:

输入包含多个测试用例,每个测试用例的第一行包含两个正整数 n、m,1=<n,m<=100000。接下来有m行,每行分别输入两个人的编号f,t(1=<f,t<=n),表示f和t是好友。 当n为0时,输入结束,该用例不被处理。

输出:

对应每个测试用例,输出在这n个人里一共有多少个朋友圈。

样例输入:
5 3
1 2
2 3
4 5
3 3
1 2
1 3
2 3
0
样例输出:
2
1
来源:
小米2013年校园招聘笔试题
#include <stdio.h>
 
#define MAX 100001
 
void Make_Set (int father[], int rank[], int n){
    int i;
    for (i=1; i<=n; ++i){
        father[i] = i;
        rank[i] = 0;
    }
}
 
int Find_Set (int father[], int x){
    if (father[x] != x){
        father[x] = Find_Set (father, father[x]);
    }
    return father[x];
}
 
void Union (int father[], int rank[], int x, int y){
    x = Find_Set (father, x);
    y = Find_Set (father, y);
    if (x == y)
        return;
    if (rank[x] > rank[y]){
        father[y] = x;
        rank[x] += rank[y];
    }
    else{
        if (rank[x] == rank[y])
            ++rank[y];
        father[x] = y;
    }
}
 
int main(void){
    int n;
    int m;
    int father[MAX];
    int rank[MAX];
    int f, t;
    int nSet;
    int i;
 
    while (scanf ("%d", &n) != EOF && n != 0){
        scanf ("%d", &m);
        Make_Set (father, rank, n);
        while (m-- != 0){
            scanf ("%d%d", &f, &t);
            Union (father, rank, f, t);
        }
        nSet = 0;
        for (i=1; i<=n; ++i){
            if (father[i] == i)
                ++nSet;
        }
        printf ("%d\n", nSet);
    }
 
    return 0;
}

参考资料: 并查集 -- 学习详解

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值