您的位置:首页 > 其它

关于"树(Tree, UVa548)“的记录

2015-09-27 17:43 295 查看
代码是书上的,感觉比较简洁,故放上
#include<iostream>
#include<string>
#include<sstream>
using namespace std;
const int maxs = 100;
int post_order[maxs], in_order[maxs], rch[maxs], lch[maxs];
int index;
bool read_list(int* a)
{
string s;
int temp;
index = 0;
if(!getline(cin, s)) return false;;
stringstream ss(s);
while(ss >> temp)
a[index++] = temp;
return index > 0;
}
int build(int L1, int R1, int L2, int R2)
{
if(R1 < L1) return 0;
int root = post_order[R2];
int p = L1;
while(in_order[p] !=  root) p++;
int n = p-L1;
lch[root] = build(L1, p-1, L2, L2+n-1);
rch[root] = build(p+1, R1, L2+n, 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);
}
void main()
{
read_list(in_order);
read_list(post_order);
build(0, index-1, 0, index-1);
best_sum = 1000000;
dfs(post_order[index-1], 0);
cout << best << endl;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  uva 菜鸟