题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1856
题 意:在1---10000000中找出直接或者间接是朋友的男生,并输出最多的人数。
思 路:使用并查集建立树,找出建立的所有树中结点最多的树的结点数。
注:
在处理数据时,一定要将数据的处理范围求出,若总是按最大的求,最后会超时。
代码如下:
#include <iostream>
using namespace std;
#include <string.h>
#include <stdio.h>
#include <queue>
#include <algorithm>
#define m 10000000
typedef long long LL;
int ben[m],sum[m];
int findx( int x )
{
int r = x;
while( r != ben[r] )
r =ben[r];
int i = x;
while( i != r )
{
int j = ben[i];
ben[i] = r;
i = j;
}
return r;
}
void mergex( int x, int y )
{
int fx = findx(x);
int fy = findx(y);
if(fx>fy)
{
ben[fx]=fy;
sum[fy]=sum[fx]+sum[fy];
}
if(fx<fy)
{
ben[fy]=fx;
sum[fx]=sum[fy]+sum[fx];
}
}
int main()
{
int n;
while( scanf ( "%d", &n) != EOF )
{
if( n == 0 ) {printf("1\n");continue;}
for( int i = 0; i <= m ; i ++ )
ben[i]=i,sum[i]=1;
int ma = 0;
for( int i = 0; i < n ; i ++ )
{
int x, y;
scanf ( "%d %d", &x, &y );
if(ma<x) ma=x;//求出数据的处理范围
if(ma<y) ma=y;
mergex(x,y);
}
int maxx=0;
for( int i = 1; i <= ma; i ++ )
{
if(sum[i]>maxx) maxx=sum[i];
}
printf("%d\n",maxx);
}
return 0;
}