UVA - 548 Tree
来源:互联网 发布:股权众筹系统源码 编辑:程序博客网 时间:2024/06/06 00:16
题目大意:给一棵树的中序遍历和后序遍历,找一叶子到根的值最小的叶子,若有多解,输出叶子本身最小的那个叶子。
解题思路:根据中序遍历和后序遍历建树。后续的最后一个数是根节点,该数在中序中的前一个数是该数的左孩子,cnt 是左子树节点个数。dfs 求解。
#include<iostream>#include<cstdio>#include<cstdlib>#include<cstring>#include<cmath>#include<ctype.h>using namespace std;int middle[10010], after[10010], lch[10010], rch[10010];int n, maxans, ans;int build(int l1, int r1, int l2, int r2) { if (l1 > r1) return 0; int root = after[r2]; int tag = l1; while (middle[tag] != root) tag++; int cnt = tag-l1; lch[root] = build(l1, tag-1, l2, l2+cnt-1); rch[root] = build(tag+1, r1, l2+cnt, r2-1); return root;}void dfs(int leaf, int sum) { sum += leaf; if (!lch[leaf] && !rch[leaf]) { if (sum < maxans || (sum == maxans && leaf < ans)) { ans = leaf; maxans = sum; } } if (lch[leaf]) dfs(lch[leaf], sum); if (rch[leaf]) dfs(rch[leaf], sum);}int main() { char c; while (scanf("%d%c", &middle[0],&c) != EOF) { n = 1; while (c != '\n') scanf("%d%c", &middle[n++], &c); for (int i = 0; i < n; i++) scanf("%d", &after[i]); build(0, n-1, 0, n-1); maxans = 999999999; dfs(after[n-1], 0); printf("%d\n", ans); }return 0;}
0 0
- UVa 548 Tree
- uva 548 Tree
- uva 548 - Tree
- uva 548 - Tree
- UVa 548 - Tree
- uva 548 Tree
- uva 548 - Tree
- 数据结构 uva 548-Tree
- UVA 548 - Tree
- UVa 548 - Tree
- UVa 548 - Tree
- uva-548 Tree
- UVA 548 Tree
- UVA 548 tree
- uva 548 -Tree
- uva 548 Tree
- 548 - Tree (UVa OJ)
- UVA 548 Tree
- jquery ajax 向后台传递数组参数示例
- UVA - 112 Tree Summing
- HDU 5753 Permutation Bo
- River Hopscotch<poj3528>
- 【HDU】1025 - Constructing Roads In JGShining's Kingdom(LIS & 深坑)
- UVA - 548 Tree
- CodeForces 427A
- CodeForces 274A k-Multiple Free Set【思维】
- UVA - 297 Quadtrees
- 面向对象
- UVA301Transportation
- JS+CSS 实现 悬浮滚动广告
- Git知识整理
- poj1213Fantasy of a Summation(找规律,优化代码)