这道题目本身不难,给出后序遍历和中序遍历,求到节点最小路径的叶子,相同长度就输出权值小的叶子。
Uva上不去了,没法测。基本上是按照ruka的代码来的。直接上代码
//Uva548 Tree
#include<iostream>
#include<algorithm>
#include<string>
#include<sstream>
#include<cctype>
using namespace std;
const int maxv=10000+10;
int inorder[maxv],postorder[maxv],l[maxv],r[maxv];
int n;
int best,best_num;
bool read_list(int *a){
string line;
if (!getline(cin,line)) return false;
stringstream ss(line);
n=0;
int x;
while (ss>>x) a[n++]=x;
return n>0;
}
int build(int l1,int r1,int l2,int r2){
if (l1>r1) return 0;//notice
int root=postorder[r2];
int p=0;
while (inorder[p]!=root) p++;
int cnt=p-l1;
l[root]=build(l1,p-1,l2,l2+cnt-1);
r[root]=build(p+1,r1,l2+cnt,r2-1);
return root;
}
void dfs(int now,int sum){
sum+=now;
if ((!l[now])&&(!r[now])){
if ((sum<best_num)||((sum==best_num)&&(now<best))){
best=now;
best_num=sum;
}
}
if (l[now]) dfs(l[now],sum);
if (r[now]) dfs(r[now],sum);
}
int main(){
freopen("1.txt","r",stdin);
freopen("2.txt","w",stdout);
while (read_list(inorder)){//every time you read an inorder
read_list(postorder);
build(0,n-1,0,n-1);//build a tree
best_num=1000000000;
dfs(postorder[n-1],0);
cout<<best<<endl;;
}
return 0;
}
五一又要出去培训了,要求相当高,我要抓紧时间学习了。
——长风破浪会有时,直挂云帆济沧海