UVA 548 树
来源:互联网 发布:产品设计建模软件 编辑:程序博客网 时间:2024/05/20 22:26
这道题的关键字在于根据中序遍历和后序遍历建立出二叉树。另外在寻找路径时,可使用深度优先的方式搜索,搜索到叶子节点时加以判断即可。
这里用到sstream来读入,也是一个技巧,记录下来。
代码如下:
#include<cstdio>#include<iostream>#include<algorithm>#include<cstring>#include<string>#include<sstream>using namespace std;const int maxn = 10005;const int root = 1;int Left[maxn], Right[maxn];int Value[maxn];int ins[maxn], pos[maxn];int n;int cnt;int bestSum = 1000000000;int best;bool getinput(int a[]){ string s; if (!getline(cin,s)) return false; stringstream ss(s); n = 0; int x; while (ss >> x){ a[n++] = x; } return true;}void newTree(){ cnt = 0; Left[root] = Right[root] = 0; Value[root] = -1;}int newNode(){ ++cnt; Left[cnt] = Right[cnt] = 0; Value[cnt] = -1; return cnt;}int build(int L1, int R1, int L2, int R2){ int t = 0; if (L1 <= R1){ int v = pos[R2]; t = newNode(); Value[t] = v; int i; for (i = L1; i <= R1; i++){ if (ins[i] == v) break; } int cnt = i - L1; Left[t] = build(L1, i - 1, L2, L2+cnt-1); Right[t] = build(i + 1, R1, L2 + cnt, R2-1); } return t;}void dfs(int p,int sum){ sum += Value[p]; if (!(Left[p] || Right[p])){ if (sum < bestSum || (sum == bestSum && Value[p] < best)){ best = Value[p]; bestSum = sum; } } else{ if (Left[p]) dfs(Left[p], sum); if (Right[p]) dfs(Right[p], sum); }}int main(){ while (getinput(ins)){ getinput(pos); newTree(); build(0, n-1, 0, n-1); bestSum = 1000000000; best = 10000; dfs(root,0); cout << best << endl; } return 0;}
阅读全文
0 0
- 重写 UVA 548 树
- uva 548(二叉树)
- UVa 548 树
- uva 548 tree 树
- 548UVa树
- UVA 548 树
- 树,UVA 548
- 二叉树 UVA 548 Tree
- UVA - 548 Tree 二叉树
- UVa--548 Tree(二叉树)
- UVA 548 Tree 【树+DFS】
- uva 548
- UVA 548
- uva 548
- uva 548
- uva 548
- uva 548
- uva 548
- 哈尔滨这家咖啡馆,灯饰和楼梯都成了“拍照道具
- Shiro基础学习(一)—权限管理
- java 抓取2016年统计用区划代码和城乡划分代码
- JavaWeb动态导出Excel可弹出下载
- 字典序全排列
- UVA 548 树
- 2013年的学习体会
- Microsoft Windows Operating System Version
- BZOJ 3407: [Usaco2009 Oct]Bessie's Weight Problem 贝茜的体重问题 背包dp
- Echarts饼图各项数值和占比显示,以及字体大小调整
- No Dialect mapping for JDBC type 0
- 前端页面接收request.setAttribute("变量名", 变量值)传的值
- daytimeUDP协议客户端与服务器交互过程
- 《悟透javascript》摘抄1.3-一首小诗