Uva 10608 Friends

题目是给出总人数,和两个人之间的朋友关系,最后求最多的朋友的人数。

思路:用并查集去求。

 1 #include <cstdio>
 2 #include <cstring>
 3 #include <iostream>
 4 using namespace std;
 5 
 6 int caseNum,citizen,pairNum;
 7 typedef struct node{
 8     int data_;//节点对应人的编号
 9     int rank_;//节点对应的秩
10     int parent_;//节点对应双亲下标
11 }UFSTree;
12 void MAKE_SET(UFSTree t[]);//初始化并查集树
13 int FIND_SET(UFSTree t[],int x);//在x所在子树中查找集合编号
14 void UNION(UFSTree t[],int x,int y);//将x和y所在的子树合并
15 int main()
16 {
17     //freopen("D:\\acm.txt","r",stdin);
18     int maxNum;
19     cin>>caseNum;
20         for(int cycle = 0;cycle < caseNum;cycle++){
21             cin>>citizen>>pairNum;
22             maxNum = 0;
23             UFSTree t[30011];
24             MAKE_SET(t);
25             for(int m = 0;m < pairNum;m++){
26                 int x,y;
27                 cin>>x>>y;
28                 UNION(t,x,y);
29             }
30             for(int op = 1;op <= citizen;op++){
31                 if(maxNum < t[op].rank_)maxNum = t[op].rank_;
32             }
33             cout<<maxNum<<endl;
34         }
35     return 0;
36 }
37 void MAKE_SET(UFSTree t[]){
38     for(int i = 1;i <= citizen;i++){
39         t[i].data_ = i;//数据为该人编号
40         t[i].rank_ = 1;
41         t[i].parent_ = i;//父节点指向自己
42     }
43 }
44 int FIND_SET(UFSTree t[],int x){
45     if(x != t[x].parent_){
46         return (FIND_SET(t,t[x].parent_));
47     }
48     else
49         return x;
50 }
51 void UNION(UFSTree t[],int x,int y){
52     x = FIND_SET(t,x);
53     y = FIND_SET(t,y);
54     if(x==y)return;
55     if(t[x].rank_ > t[y].rank_){
56             t[y].parent_ = x;
57             t[x].rank_ += t[y].rank_;
58     }
59     else{
60         t[x].parent_ = y;
61         t[y].rank_ += t[x].rank_;
62     }
63 }

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值