24h購物| | PChome| 登入
2012-06-08 22:11:06| 人氣1,105| 回應0 | 上一篇 | 下一篇

[UVA][graph] 548 - Tree

推薦 0 收藏 0 轉貼0 訂閱站台


  Tree 

You are to determine the value of the leaf node in a given binary tree that is the terminal node of a path of least value from the root of the binary tree to any leaf. The value of a path is the sum of values of nodes along that path.

Input 

The input file will contain a description of the binary tree given as the inorder and postorder traversal sequences of that tree. Your program will read two line (until end of file) from the input file. The first line will contain the sequence of values associated with an inorder traversal of the tree and the second line will contain the sequence of values associated with a postorder traversal of the tree. All values will be different, greater than zero and less than 10000. You may assume that no binary tree will have more than 10000 nodes or less than 1 node.

Output 

For each tree description you should output the value of the leaf node of a path of least value. In the case of multiple paths of least value you should pick the one with the least value on the terminal node.

Sample Input 

3 2 1 4 5 7 6
3 1 2 5 6 7 4
7 8 11 3 5 16 12 18
8 3 11 7 16 18 12 5
255
255

Sample Output 

1
3
255

 
#include <stdio.h>
#include <iostream>
#include <sstream>
using namespace std;
int in[10000], post[10000], n;
int bst[10000][2], pa;
void build(int l, int r, int p, int flag) {
if(l > r)
return;
int i, ppa = pa;
for(i = l; i <= r; i++) {
if(in[i] == post[pa]) {
break;
}
}
if(p != -1)
bst[p][flag] = pa;
pa--;
build(i+1, r, ppa, 1);
build(l, i-1, ppa, 0);
}
int min_sum, ans;
void dfs(int nd, int sum) {
if(bst[nd][0] == -1 && bst[nd][1] == -1) {
if(sum < min_sum)
min_sum = sum, ans = post[nd];
if(sum == min_sum && ans > post[nd])
ans = post[nd];
return;
}
if(bst[nd][0] != -1)
dfs(bst[nd][0], sum+post[bst[nd][0]]);
if(bst[nd][1] != -1)
dfs(bst[nd][1], sum+post[bst[nd][1]]);
}
int main() {
string line;
stringstream sin;
int i;
while(getline(cin, line)) {
sin.clear();
sin << line;
i = 0;
while(sin >> in[i])
i++;
getline(cin, line);
sin.clear();
sin << line;
i = 0;
while(sin >> post[i])
i++;
n = i, pa = n-1;
for(i = 0; i < n; i++)
bst[i][0] = -1, bst[i][1] = -1;
build(0, n-1, -1, 0);
min_sum = 0xfffffff;
dfs(n-1, 0);
printf("%d\n", ans);
}
return 0;
}

台長: Morris
人氣(1,105) | 回應(0)| 推薦 (0)| 收藏 (0)| 轉寄
全站分類: 不分類 | 個人分類: UVA |
此分類下一篇:[UVA][java] 10523 - Very Easy !!!
此分類上一篇:[UVA] 320 - Border

是 (若未登入"個人新聞台帳號"則看不到回覆唷!)
* 請輸入識別碼:
請輸入圖片中算式的結果(可能為0) 
(有*為必填)
TOP
詳全文