zoukankan      html  css  js  c++  java
  • 【日常学习】【二叉树遍历】Uva548

    这道题目本身不难,给出后序遍历和中序遍历,求到节点最小路径的叶子,同样长度就输出权值小的叶子。

    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;
    } 

    五一又要出去培训了。要求相当高。我要抓紧时间学习了。

    ——长风破浪会有时,直挂云帆济沧海

  • 相关阅读:
    声明式事务
    创建索引之代码开发
    Lucene实现全文检索的流程
    9)添加对话框的按键处理消息
    8)添加一个新的非模态对话框
    7)给tab下面添加一个子非模态对话框
    6)对(5)的代码进行一下修改 但是功能不变
    5)添加一个tab
    4)创建一个简单页面
    3)为啥(2)的代码那么写的原因
  • 原文地址:https://www.cnblogs.com/jhcelue/p/6850161.html
Copyright © 2011-2022 走看看