【 UVA - 548 】 Tree (静态建树+DFS)
发布日期:2021-05-04 19:24:19 浏览次数:24 分类:原创文章

本文共 1135 字,大约阅读时间需要 3 分钟。


题意:

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


代码:

#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;}
上一篇:【 UVA - 572 】 Oil Deposits (DFS水题)
下一篇:【 HDU - 1175 】 O - 连连看 (DFS)

发表评论

最新留言

哈哈,博客排版真的漂亮呢~
[***.90.31.176]2025年03月27日 06时42分56秒