ZOJ 3805 Machine

举报
Linux猿 发表于 2021/08/05 00:41:32 2021/08/05
【摘要】 题目链接~~> 做题感悟:比赛时想到方法了,但是没能AC,很遗憾,没有考虑到左右子树的右节点相等的情况,结果就杯具了,比赛完后捋了一下思路就AC了,说明比赛时很不淡定,头脑不清醒,以后要注意。 解题思路:                 题目给的就是一颗树,只是要把右节点多的放到左儿...

题目链接~~>

做题感悟:比赛时想到方法了,但是没能AC,很遗憾,没有考虑到左右子树的右节点相等的情况,结果就杯具了,比赛完后捋了一下思路就AC了,说明比赛时很不淡定,头脑不清醒,以后要注意。

解题思路:

                题目给的就是一颗树,只是要把右节点多的放到左儿子上就好,这样减少个数,递归一下,注意左右儿子节点相等的情况需要加 1 。

代码:


  
  1. #include<iostream>
  2. #include<sstream>
  3. #include<map>
  4. #include<cmath>
  5. #include<fstream>
  6. #include<queue>
  7. #include<vector>
  8. #include<sstream>
  9. #include<cstring>
  10. #include<cstdio>
  11. #include<stack>
  12. #include<bitset>
  13. #include<ctime>
  14. #include<string>
  15. #include<cctype>
  16. #include<iomanip>
  17. #include<algorithm>
  18. using namespace std ;
  19. #define INT __int64
  20. #define L(x) (x * 2)
  21. #define R(x) (x * 2 + 1)
  22. const int INF = 0x3f3f3f3f ;
  23. const double esp = 0.0000000001 ;
  24. const double PI = acos(-1.0) ;
  25. const int mod = 1000000007 ;
  26. const int MY = (1<<5) + 5 ;
  27. const int MX = 100000 + 5 ;
  28. int n ;
  29. struct node
  30. {
  31. int le ,rt ;
  32. }T[MX] ;
  33. int dfs(int u) // 转变左右子树,计算有几个右儿子
  34. {
  35. int Lson = 0 ,Rson = 0 ,num = 0 ;
  36. if(T[u].le) // 计算左子树
  37. Lson = dfs(T[u].le) ;
  38. if(T[u].rt) // 计算右子树
  39. Rson = dfs(T[u].rt) ;
  40. if(Lson < Rson) // 如果左子树的右儿子小于右子树的右儿子
  41. swap(T[u].le ,T[u].rt) ;
  42. if(Lson == Rson) return Lson + 1 ; // 注意
  43. return max(Lson ,Rson) ;
  44. }
  45. int main()
  46. {
  47. //freopen("input.txt" ,"r" ,stdin) ;
  48. int x ;
  49. while(~scanf("%d" ,&n))
  50. {
  51. memset(T ,0 ,sizeof(T)) ;
  52. for(int i = 2 ;i <= n ; ++i)
  53. {
  54. scanf("%d" ,&x) ;
  55. if(T[x].le)
  56. T[x].rt = i ;
  57. else T[x].le = i ;
  58. }
  59. printf("%d\n" ,dfs(1)) ;
  60. }
  61. return 0 ;
  62. }


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

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

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

评论(0

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

全部回复

上滑加载中

设置昵称

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

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

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