HDOJ 1856 More is better

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

ContractedBlock.gif ExpandedBlockStart.gif View Code
 1 #include    
2 #include
3 unsigned value[10000001];
4 unsigned maxRecord[10000001];
5 unsigned maxValue;
6 unsigned find(unsigned v)
7 {
8 unsigned temp=v;
9 while (value[v]!=-1)
10 {
11 v=value[v];
12 }
13 unsigned j;
14 while (temp!=v)//路径压缩
15 {
16 j=value[temp];
17 value[temp]=v;
18 temp=j;
19 }
20 return v;
21 }
22 void unionSet(unsigned x,unsigned y)
23 {
24 unsigned px=find(x);
25 unsigned py=find(y);
26 if(px==py)
27 return ;
28 value[py]=px;
29 maxRecord[px]+=maxRecord[py];
30 if(maxRecord[px]>maxValue)
31 maxValue=maxRecord[px];
32 }
33 int main()
34 {
35 //freopen("More is better.txt","r",stdin);
36
37 unsigned num,fValue,sValue;
38 while(scanf("%u",&num)!=EOF)
39 {
40 memset(value,-1,sizeof(value));
41 for (int i=0;i<10000001;i++)
42 maxRecord[i]=1;
43 maxValue=1;//设置起始值
44 for (unsigned i=0;i45 {
46 scanf("%u%u",&fValue,&sValue);
47 unionSet(fValue,sValue);
48 }
49 printf("%u\n",maxValue);
50 }
51 }

转载于:https://www.cnblogs.com/AdaByron/archive/2011/09/18/2200974.html

你可能感兴趣的:(HDOJ 1856 More is better)