【例题 6-8 UVA - 548】Tree

【链接】 我是链接,点我呀:)
【题意】

在这里输入题意

【题解】

后序遍历的最后一个是根节点。 ->然后在中序遍历中找到这个节点。 分为左右两段. 然后递归上述操作就好。 题目描述好坑啊。 原来是叶子节点的权值的最小值。。 (叶子节点到根节点的权值和最小的对应的叶子节点的最小权值,,,)

【代码】

#include <bits/stdc++.h>
using namespace std;
#define ll long long

const int N = 1e4;
const ll INF = 1e18;

string s;
int zx[N+10],hx[N+10],n,g[N+10][2],val[N+10],cnt;
int idx[N+10],cur,ansi = N+10;
ll ans = INF;

void init(int a[]){
	stringstream ss(s);
	n = 1;
	while (ss>>a[n]){
		n++;
	}
	n--;
}

void dfs1(int x,int l,int r){
	val[x] = hx[cur];
	int mid = idx[hx[cur]];
	cur--;
	if (mid<r) {
		if (!g[x][1]) g[x][1] = ++cnt;		
		dfs1(g[x][1],mid+1,r);
	}

	if (l < mid){
		if (!g[x][0]) g[x][0] = ++cnt;
		dfs1(g[x][0],l,mid-1);
	}
}

void dfs(int x,ll sum){
	if (!g[x][0] && !g[x][1]){
		if (sum < ans){
			ans = sum;
			ansi = val[x];
		}else if (ans==sum)
			ansi = min(ansi,val[x]);			
		return;
	}
	if (g[x][0]) dfs(g[x][0],sum+val[g[x][0]]);
	if (g[x][1]) dfs(g[x][1],sum+val[g[x][1]]);
}

int main(){
//	freopen("rush.txt","r",stdin);
	while (getline(cin,s)){
		ans = INF,ansi = N+2;
		cnt = 1;
		memset(g,0,sizeof g);
		init(zx);
		getline(cin,s);
		init(hx);
		for (int i = 1;i <= n;i++) idx[zx[i]] = i;
		cur = n;
		dfs1(1,1,n); 
		dfs(1,val[1]);          
		printf("%lld\n",ansi);	
	}
	return 0;
}
posted @ 2017-10-20 21:18  AWCXV  阅读(160)  评论(0编辑  收藏  举报