HDU1856 - More is better: http://acm.hdu.edu.cn/showproblem.php?pid=1856
题意: a和b认识,b和c认识,则a b c互相认识. 给出一些相互认识的两个人的编号. 判断最多有多少人互相认识(包括自己).
代码:
#include <iostream>
#include <cstring>
#include <cstdio>
using namespace std;
const int MAXN = 100011;
int N;
int x,y;
int MaxId,MaxNum,Num[MAXN],Father[MAXN];
void Initial()
{
MaxId = MaxNum = -1;
for(int i = 0;i < MAXN;i++)
Father[i] = i,Num[i] = 1;//Num数组的元素都初始化为 1,最少有一个人
}
int Find(int x)
{
/* if(x != Father[x])
Father[x] = Find(Father[x]);
return Father[x];
*/
return x == Father[x] ? Father[x] : Father[x] = Find(Father[x]);
}
void Union(int x,int y)
{
x = Find(x);
y = Find(y);
if(x != y)
Father[x] = y,Num[y] += Num[x];//合并的同时将人数加到根节点上,这里要注意,不要写反了
}
int main()
{
while(~scanf("%d",&N))
{
if(!N)
{
printf("1\n");
continue;
}
Initial();
while(N--)
{
scanf("%d%d",&x,&y);
//这里求出出现过的id最大为MaxId,因为这里是千万的数量级,全部循环一次会耗费较多的时间
if(MaxId < x)MaxId = x;
if(MaxId < y)MaxId = y;
Union(x,y);
}
for(int i = 0;i <= MaxId;i++)//找出最大的人数
if(MaxNum < Num[i])
MaxNum = Num[i];
printf("%d\n",MaxNum);
}
return 0;
}