码迷,mamicode.com
首页 > 其他好文 > 详细

Uva 10608 Friends

时间:2014-11-17 01:39:22      阅读:176      评论:0      收藏:0      [点我收藏+]

标签:style   blog   io   color   ar   os   sp   for   数据   

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

思路:用并查集去求。

 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 }

 

Uva 10608 Friends

标签:style   blog   io   color   ar   os   sp   for   数据   

原文地址:http://www.cnblogs.com/ohxiaobai/p/4095943.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!