记录编号 279720 评测结果 AAAAA
题目名称 [UVa 548] 树 最终得分 100
用户昵称 Gravatar@@@ 是否通过 通过
代码语言 C++ 运行时间 0.001 s
提交时间 2016-07-09 16:13:49 内存使用 0.46 MiB
显示代码纯文本
  1. #include<iostream>
  2. #include<cstdio>
  3. #include<string>
  4. #include<sstream>
  5. #include<algorithm>
  6. using namespace std;
  7. const int maxv=10000+10;
  8. int in_order[maxv],post_order[maxv],lch[maxv],rch[maxv];
  9. int n;
  10. bool read_list(int* a){
  11. string line;
  12. if(!getline(cin,line)) return false;
  13. stringstream ss(line);
  14. n=0;
  15. int x;
  16. while(ss>>x) a[n++]=x;
  17. return n>0;
  18. }
  19. int build(int L1,int R1,int L2,int R2){
  20. if(L1>R1) return 0;
  21. int root=post_order[R2];
  22. int p=L1;
  23. while(in_order[p]!=root) p++;
  24. int cnt=p-L1;
  25. lch[root]=build(L1,p-1,L2,L2+cnt-1);
  26. rch[root]=build(p+1,R1,L2+cnt,R2-1);
  27. return root;
  28. }
  29. int best,best_sum;
  30. void dfs(int u,int sum){
  31. sum+=u;
  32. if(!lch[u] && !rch[u]){
  33. if(sum<best_sum||(sum==best_sum&&u<best)){
  34. best=u;best_sum=sum;
  35. }
  36. }
  37. if(lch[u]) dfs(lch[u],sum);
  38. if(rch[u]) dfs(rch[u],sum);
  39. }
  40. int main(){
  41. freopen("sumtree.in", "r", stdin);
  42. freopen("sumtree.out", "w", stdout);
  43. while(read_list(in_order)){
  44. read_list(post_order);
  45. build(0,n-1,0,n-1);
  46. best_sum=1000000000;
  47. dfs(post_order[n-1],0);
  48. cout<<best<<"\n";
  49. }
  50. return 0;
  51. }