uva 548 Tree
2016-05-25 08:44
357 查看
#include<iostream> #include<cstdio> #include<sstream> using namespace std; const int maxv=10000+10; int in_order[maxv],post_order[maxv],lch[maxv],rch[maxv]; int n; bool read_list(int *a) { string line; if(!getline(cin,line)) return false; stringstream ss(line); n=0; int x; while(ss>>x) a[n++]=x; return true; } int buildtree(int L1,int R1,int L2,int R2) { if(L1>R1) return 0; int root=post_order[R2]; int p=L1; while(in_order[p]!=root) p++; int len=p-L1; lch[root]=buildtree(L1,p-1,L2,L2+len-1); rch[root]=buildtree(p+1,R1,L2+len,R2-1); return root; } int best_sum=10000000,best; void dfs(int u,int sum) { sum+=u; if(!lch[u]&&!rch[u]) { if(best_sum>sum||(best_sum==sum&&u<best)) {best=u;best_sum=sum;} } if(lch[u]) dfs(lch[u],sum); if(rch[u]) dfs(rch[u],sum); } int main() { while(read_list(in_order)) { read_list(post_order); buildtree(0,n-1,0,n-1); int u=post_order[n-1]; best_sum=1000000; dfs(u,0); cout<<best<<endl; } return 0; }
相关文章推荐
- bzoj 3149: [Ctsc2013]复原 dfs
- java入门教程-3.5Java方法重载
- nw.js 系列帖子搜集
- iis.bat、w3wp.bat
- GitHub使用过程中push出错的解决办法
- oracle锁表后,系统能否自动解锁?
- Windows下批处理的使用
- SCU 4512 Goozy的积木(dp)
- 每天一个Linux命令(27)gzip命令
- python中的深拷贝和浅拷贝理解
- 微服务以及测试必要性
- java入门教程-3.4Java this关键字详解
- 安卓开发中常见的屏幕适配方法
- SharedPreferences
- 13-Ajax链接与Ajax表单的快速对比Demo
- 入门超简单python入门神图
- ORACLE中的varchar2()与nvarchar2()的讲解
- vs2010遇到 模块计算机类型“X86”与目标计算机类型“x64”冲突
- Open-E DSS V7 应用系列之十 主动/主动 iSCSI群集部署(二)
- Color Spaces