UVa--548 Tree(二叉树)
来源:互联网 发布:linux 制作iso 编辑:程序博客网 时间:2024/05/21 04:21
UVa 548
题解
根据中序后序序列直接建立(lch[], rch[]),表示结点的左右子节点的权值。
#include <iostream>#include <cstdio>#include <string>#include <sstream>#include <climits>#include <algorithm>using namespace std;const int maxn = 10000 + 10;int inorder[maxn], postorder[maxn], lch[maxn], rch[maxn];int n;bool read(int* a){ string line; if(!getline(cin, line)) return false; stringstream ss(line); int x; n = 0; while(ss >> x) a[n++] = x; return n > 0;}// inorder[L1..R1], postorder[L2..R2]int build(int L1, int R1, int L2, int R2){ if(L1 > R1) return 0; int root = postorder[R2]; int p = L1; while(inorder[p] != root) p++; int cnt = p - L1; lch[root] = build(L1, p - 1, L2, L2 + cnt - 1); rch[root] = build(p + 1, R1, L2 + cnt, 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);}int main(){#ifdef LOCALfreopen("data.in", "r", stdin);#endif // LOCAL while(read(inorder)){ read(postorder); build(0, n - 1, 0, n - 1); best_sum = INT_MAX; dfs(postorder[n - 1], 0); cout << best << endl; } return 0;}
0 0
- 二叉树 UVA 548 Tree
- UVA - 548 Tree 二叉树
- UVa--548 Tree(二叉树)
- UVA 548 Tree(数据结构,二叉树,遍历)
- UVA 548-Tree(二叉树)
- UVa 548 - Tree(二叉树)
- UVA 548Tree(二叉树建树)
- 【UVA 548 Tree】二叉树构造 & 遍历
- UVa 548 - Tree 二叉树的重建与遍历
- UVA 548 Tree(二叉树的建立)
- UVa 548 - Tree【二叉树的递归遍历(DFS)】
- uva 548 tree 二叉树的各种遍历
- Uva-548-Tree(二叉树与stream与dfs)
- UVA 548 Tree(中序+后序还原二叉树)
- Uva 248 Tree//二叉树遍历,递归
- UVa 536 Tree Recobery 二叉树重建
- UVA 546 Tree (二叉树综合运用)
- uva 536 Tree Recovery(二叉树重建)
- PAT-乙级-1024. 科学计数法 (20)
- Javascript数据类型
- Unix下五种I/O模型
- java实现选择排序
- eclipse快捷键的使用
- UVa--548 Tree(二叉树)
- 日常笔记:Python(1)
- GDKOI 2016 魔卡少女
- gradle多渠道打包和同一App打包不同版本Api调用
- 创建Red Hat Enterprise Linux 6 64位虚拟机
- python中的sys模块函数
- stdlib.h
- Recommender System Fragment 1
- 区间选点问题---poj-1328