HDOJ 1856 More is better
2011-09-18 10:35
239 查看
此题与典型的并查集不同的是,此题要求输出每棵树上节点的个数,所以要考虑的是如何处理节点个数的问题。最后逐个遍历相对于10000000个数据来说显然不是个好方法。仍然是牺牲空间换时间的思想,在‘并’和‘查’的同时将树中的节点个数记录到父节点中。由于数据量较大,所以考虑使用路径压缩。此题中要求了最终至少要有一个(or
there is only one boy left)所以记录最大点数的起始值要从1开始才好。参考代码如下:
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); } }
相关文章推荐
- hdoj-1856-More is better
- hdoj 1856 More is better 【并查集 求最大节点数】
- HDOJ1856 More is better 【并查集】
- HDOJ 1856 More is better
- HDOJ 1856 More is better 杭电 ACM
- hdoj 1856 More is better 【并查集 求最大节点数】
- HDOJ 1856 More is better
- HDOJ 1856 More is better
- hdoj-1856-More is better【并查集】
- hdoj 1856 More is better
- HDOJ HDU 1856 More is better ACM 1856 IN HDU
- hdoj 1856 More is better 【rank[]】
- hdoj1856_More is better
- hdoj 1856 More is better
- HDOJ 1856 More is better (并查集)
- HDOJ-1856 More is better&&POJ-1611(并查集)
- HDOJ 1856 More is better
- hdoj-1856-More is better【并查集】
- hdoj 1856 More is better(并查集)
- HDOJ 1856 More is better (并查集 + 压缩路径 + 结点深度)