【 UVA - 548 】 Tree (静态建树+DFS)

题目传送


题意:

给定中序遍历和后序遍历,然后建树,最后找出一个叶子到根的路径权值最小(权和相同时,选择叶子权值小的那个)。


代码:

#include<iostream>
#include<algorithm>
#include<cstring>
#include<sstream>
#include<cstdio>
#include<queue>
#include<cmath>
#include<set> 
#include<map>
using namespace std; 
const int maxn=1e4+50;
int in[maxn],post[maxn],lch[maxn],rch[maxn]; //中序,后序,左子树,右子树
int x,c,ans,sumans;
string s;

int build(int zz,int zy,int hz,int hy)  //静态建树
          // 中左(中序遍历第一个)  中右(中序遍历最后一个)  后左  后右 
{
	if(hz>hy) return 0;
	int root=post[hy];
	int p=zz;
	for(;p<=zy;p++) if(root==in[p]) break;
	int num=p-zz;
	lch[root]=build(zz,p-1,hz,hz+num-1);
	rch[root]=build(p+1,zy,hz+num,hy-1);
	return root;
}

void dfs(int u,int sum) //从根出发找到叶子
{
	sum+=u;
	if(!lch[u] && !rch[u]) //叶子
	{
		if(sumans>sum || (sumans==sum && u<ans)) 
		{
			ans=u;
			sumans=sum;
		}
	}
	if(lch[u]) dfs(lch[u],sum);
	if(rch[u]) dfs(rch[u],sum);
}


int main()
{	
	while(getline(cin,s))
	{
		stringstream ss(s);
		c=0;
		while(ss>>x) in[c++]=x;
	    
	    c=0;
	    getline(cin,s);
	    stringstream sss(s);
	    while(sss>>x) post[c++]=x;
	    
	    build(0,c-1,0,c-1); 
	    sumans=1<<27; //初始,很大的值
	    dfs(post[c-1],0);
	    cout<<ans<<endl;
	}
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值