HDU 1856 More is better

举报
Linux猿 发表于 2021/08/05 22:55:39 2021/08/05
【摘要】 题目链接~~> 做题感悟:这题是并查集按个数合并的运用。 解题思路:只要将父亲节点存整个树的节点数,并且每次更新最大值就可以了(ps: n==0 时输出 1)。具体讲解见: 代码: #include<stdio.h>#include<iostream>#include<map>#include<stack>#inc...

题目链接~~>

做题感悟:这题是并查集按个数合并的运用。

解题思路:只要将父亲节点存整个树的节点数,并且每次更新最大值就可以了(ps: n==0 时输出 1)。具体讲解见:

代码:


  
  1. #include<stdio.h>
  2. #include<iostream>
  3. #include<map>
  4. #include<stack>
  5. #include<string>
  6. #include<string.h>
  7. #include<stdlib.h>
  8. #include<math.h>
  9. #include<vector>
  10. #include<queue>
  11. #include<algorithm>
  12. using namespace std ;
  13. #define LEN sizeof(struct node)
  14. const double PI = 3.1415926 ;
  15. const double INF = 99999999 ;
  16. const int MX =10000005 ;
  17. int father[MX] ;
  18. int find(int x) // 路径压缩
  19. {
  20. return father[x] < 0 ? x : father[x]=find(father[x]) ;
  21. }
  22. int main()
  23. {
  24. int n ;
  25. while(~scanf("%d",&n))
  26. {
  27. for(int i=1 ;i<=10000000 ;i++)
  28. father[i]=-1 ;
  29. int best=-1,ax,ay,x,y ;
  30. for(int i=0 ;i<n ;i++)
  31. {
  32. scanf("%d%d",&x,&y) ;
  33. ax=find(x) ;
  34. ay=find(y) ;
  35. if(ax!=ay)
  36. {
  37. if(father[ax]<father[ay])
  38. {
  39. father[ax]+=father[ay] ;
  40. father[ay]=ax ;
  41. best = father[ax] < best ? father[ax] : best ;
  42. }
  43. else
  44. {
  45. father[ay]+=father[ax] ;
  46. father[ax]=ay ;
  47. best = father[ay] < best ? father[ay] : best ;
  48. }
  49. }
  50. }
  51. printf("%d\n",-best) ;
  52. }
  53. return 0 ;
  54. }


 

 

文章来源: blog.csdn.net,作者:Linux猿,版权归原作者所有,如需转载,请联系作者。

原文链接:blog.csdn.net/nyist_zxp/article/details/21820711

【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。