您的位置:首页 > 其它

HDOJ 1856 More is better

2011-09-18 10:35 239 查看
          此题与典型的并查集不同的是,此题要求输出每棵树上节点的个数,所以要考虑的是如何处理节点个数的问题。最后逐个遍历相对于10000000个数据来说显然不是个好方法。仍然是牺牲空间换时间的思想,在‘并’和‘查’的同时将树中的节点个数记录到父节点中。由于数据量较大,所以考虑使用路径压缩。此题中要求了最终至少要有一个(or
there is only one boy left)所以记录最大点数的起始值要从1开始才好。参考代码如下:

#include <stdio.h>
#include <memory.h>
unsigned value[10000001];
unsigned maxRecord[10000001];
unsigned maxValue;
unsigned find(unsigned v)
{
unsigned temp=v;
while (value[v]!=-1)
{
v=value[v];
}
unsigned j;
while (temp!=v)//路径压缩
{
j=value[temp];
value[temp]=v;
temp=j;
}
return v;
}
void unionSet(unsigned x,unsigned y)
{
unsigned px=find(x);
unsigned py=find(y);
if(px==py)
return ;
value[py]=px;
maxRecord[px]+=maxRecord[py];
if(maxRecord[px]>maxValue)
maxValue=maxRecord[px];
}
int main()
{
//freopen("More is better.txt","r",stdin);

unsigned num,fValue,sValue;
while(scanf("%u",&num)!=EOF)
{
memset(value,-1,sizeof(value));
for (int i=0;i<10000001;i++)
maxRecord[i]=1;
maxValue=1;//设置起始值
for (unsigned i=0;i<num;i++)
{
scanf("%u%u",&fValue,&sValue);
unionSet(fValue,sValue);
}
printf("%u\n",maxValue);
}
}


 

 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: