您的位置:首页 > 其它

ACM篇:Uva 548 -- Tree

2017-01-11 10:46 399 查看
#include <iostream>
#include <cstdio>
#include <vector>
#include <algorithm>
#include <cstring>
#include <sstream>
#include <cmath>
using namespace std;
const int SUP = 999999999;
struct Node
{
int val;
Node *left;
Node *right;
Node(int v): val(v), left(NULL), right(NULL) {}
};

vector<int> in_order;
vector<int> post_order;
int read_list(vector<int> &a)
{
static string line;
if (!getline(cin, line))
return 0;
stringstream ss(line);
int v;
a.clear();
while (ss >> v)
a.push_back(v);
return a.size();
}

Node *root = NULL;
void remove_tree(Node *u)
{
if (!u)
return;
remove_tree(u->left);
remove_tree(u->right);
delete u;
}
Node *build_tree(int l, int r, int ll, int rr)
{
Node *ret = new Node(post_order[rr]);
int p = l;
int cnt = 0;
while (in_order[p] != ret->val)
{
p++;
cnt++;
}
if (cnt > 0)
ret->left = build_tree(l, l+cnt-1, ll, ll+cnt-1);
if (rr-1 >= ll+cnt)
ret->right = build_tree(p+1, r, ll+cnt, rr-1);
return ret;
}

int min_sum;
int best_val;
void _dfs(Node *u, int sum)
{
sum += u->val;
if (!u->left && !u->right)
{
if (sum < min_sum || (sum == min_sum && u->val < best_val))
{
min_sum = sum;
best_val = u->val;
}
return;
}
4000

if (u->left)
_dfs(u->left, sum);
if (u->right)
_dfs(u->right, sum);

}
int main()
{
int n;
while (n = read_list(in_order))
{
read_list(post_order);
remove_tree(root);
root = build_tree(0, n-1, 0, n-1);

min_sum = best_val = SUP;
_dfs(root, 0);
printf("%d\n", best_val);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: