关于"树(Tree, UVa548)“的记录
2015-09-27 17:43
295 查看
代码是书上的,感觉比较简洁,故放上
#include<iostream> #include<string> #include<sstream> using namespace std; const int maxs = 100; int post_order[maxs], in_order[maxs], rch[maxs], lch[maxs]; int index; bool read_list(int* a) { string s; int temp; index = 0; if(!getline(cin, s)) return false;; stringstream ss(s); while(ss >> temp) a[index++] = temp; return index > 0; } int build(int L1, int R1, int L2, int R2) { if(R1 < L1) return 0; int root = post_order[R2]; int p = L1; while(in_order[p] != root) p++; int n = p-L1; lch[root] = build(L1, p-1, L2, L2+n-1); rch[root] = build(p+1, R1, L2+n, R2-1); return root; } int best, best_sum; void dfs(int u, int sum)//从根节点开始深度搜索 { sum += u; if(!lch[u] && !rch[u]) { if(sum < best_sum || (sum == best_sum && u < best)) { best = u; best_sum = sum; } } if(lch[u]) dfs(lch[u], sum); if(rch[u]) dfs(rch[u], sum); } void main() { read_list(in_order); read_list(post_order); build(0, index-1, 0, index-1); best_sum = 1000000; dfs(post_order[index-1], 0); cout << best << endl; }
相关文章推荐
- 菜鸟必看网络名词
- 菜鸟网赚高级技巧
- 40个迹象表明你还是PHP菜鸟
- 网络菜鸟的五大特征,看看你身边有多少?
- 菜鸟入门 Linux知识大全
- 一篇超频菜鸟必看的基础知识大全!
- 菜鸟如何构建一个入门级***检测系统
- 如何从网络菜鸟成长为网络技术高手
- 代理、肉鸡、跳板的概念
- 操作秘籍 高手电脑使用心得荟萃
- 网管和***都必须知道的命令
- 菜鸟的阶段收获
- 如何学习
- 1.10055 - Hashmat the brave warrior
- 2.10071 - Back to High School Physics
- 3.458 - The Decoder
- 4.694 - The Collatz Sequence
- 6.494 - Kindergarten Counting Game
- 7.490 - Rotating Sentences
- 8.414 - Machined Surfaces