hdu 1856 关于并查集的(简单) 我老是WA

money939 2010-07-27 05:30:38
http://acm.hdu.edu.cn/showproblem.php?pid=1856
地址啊!~~~~~~~~~~

Problem Description
Mr Wang wants some boys to help him with a project. Because the project is rather complex, the more boys come, the better it will be. Of course there are certain requirements.

Mr Wang selected a room big enough to hold the boys. The boy who are not been chosen has to leave the room immediately. There are 10000000 boys in the room numbered from 1 to 10000000 at the very beginning. After Mr Wang's selection any two of them who are still in this room should be friends (direct or indirect), or there is only one boy left. Given all the direct friend-pairs, you should decide the best way.



Input
The first line of the input contains an integer n (0 ≤ n ≤ 100 000) - the number of direct friend-pairs. The following n lines each contains a pair of numbers A and B separated by a single space that suggests A and B are direct friends. (A ≠ B, 1 ≤ A, B ≤ 10000000)


Output
The output in one line contains exactly one integer equals to the maximum number of boys Mr Wang may keep.



Sample Input
4
1 2
3 4
5 6
1 6
4
1 2
3 4
5 6
7 8


Sample Output
4
2

Hint
A and B are friends(direct or indirect), B and C are friends(direct or indirect),
then A and C are also friends(indirect).

In the first sample {1,2,5,6} is the result.
In the second sample {1,2},{3,4},{5,6},{7,8} are four kinds of answers.


#include <stdio.h>

#define MM 10000009

int a[MM];

int b[MM];



int find(int x)

{

if(a[x]==x)

return x;

else

return a[x]=find(a[x]);////////递归调用找到根节点

}



int umax;



void hb(int x,int y)

{



x=find(x);

y=find(y);



if(b[x]<b[y])

{

a[x]=y;

b[y]+=b[x];

if(b[y]>umax)

umax=b[y];///////////////用来当前记录最大值

}

else

{

a[y]=x;

b[x]+=b[y];

if(b[x]>umax)

umax=b[x];

}

}





int main()

{

int i,j,k,m,n;

while(scanf("%d",&k)!=EOF)

{

if(k==0)

{

printf("1\n");

continue;

}



for(i=1;i<MM;i++)

{

a[i]=i;



b[i]=1;

}



umax=1;



for(i=0;i<k;i++)

{

scanf("%d%d",&m,&n);

if(m!=n)

hb(m,n);

}





printf("%d\n",umax);



}

return 0;

}



房间里面有10000000个人,每个人的编号从1到10000000,

一开始输入数据4,代表接下来有四个关系,
1 2就是1和2是朋友 3 4是朋友 5 6是朋友 1 6是朋友 朋友的朋友也是朋友

所以1 2 5 6是朋友 那么在这个房间里朋友数最多的团体的人数是4人。就输出结果



我先谢谢大家了,我已经问了学校里好几个大牛了都说看不出来啊!
...全文
193 2 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
logiciel 2010-07-28
  • 打赏
  • 举报
回复
上面注释错了,应是:

if (x != y)//新加条件

logiciel 2010-07-28
  • 打赏
  • 举报
回复
在函数hb中增加一个条件可以AC:

void hb(int x,int y)
{
x=find(x);
y=find(y);
if (x != y)
{
if(b[x]<b[y]) //新加条件
{
a[x]=y;
b[y]+=b[x];
if(b[y]>umax)
umax=b[y];///////////////用来当前记录最大值
}
else
{
a[y]=x;
b[x]+=b[y];
if(b[x]>umax)
umax=b[x];
}
}
}

15,447

社区成员

发帖
与我相关
我的任务
社区描述
C/C++ 非技术区
社区管理员
  • 非技术区社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧