uva548 (建树)二种方式实现 简单易懂
来源:互联网 发布:大商创开源破解版源码 编辑:程序博客网 时间:2024/05/17 06:31
数组实现
#include <iostream>#include <sstream>#include <string>#define maxn 10000+10using namespace std;int inorder[maxn],post[maxn],lch[maxn],rch[maxn];int n;bool read(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; int root=post[R2]; int p=L1; while(inorder[p]!=root)p++; int cnt=p-L1; lch[root]=build(L1,p-1,L2,L2+cnt-1); rch[root]=build(p+1,R1,L2+cnt,R2-1); return root;}int best_sum,best;void dfs(int u,int sum ){ sum+=u; if(!lch[u]&&!rch[u]) { if(best_sum>sum||(best_sum==sum&&u<best)) { best_sum=sum; best=u; } } if(lch[u])dfs(lch[u],sum); if(rch[u])dfs(rch[u],sum);}int main(){ while(read(inorder)) { read(post); build(0,n-1,0,n-1); best_sum=1000000000; dfs(post[n-1],0); cout<<best<<endl; } return 0;}
指针实现
#include <iostream>#include <stdio.h>#include <stdlib.h>#define maxn 10000+10using namespace std;int Inorder[maxn],Post[maxn];int cnt,ans;int best_sum,best;typedef struct BiNode{ int data; struct BiNode *left,*right;} BiNode,*BiTree;//BiNode node[maxn];////BiTree NewNode()//{// node[ans].left=NULL;// node[ans].right=NULL;// return &node[ans++];//}void input(){ cnt=1; while(getchar()!='\n') scanf("%d",&Inorder[cnt++]); for(int i=-0; i<cnt; i++) cin>>Post[i];}BiTree Creat(int *mid,int *post,int len){ if(len==0) return NULL; int p=len-1; while(mid[p]!=post[len-1])--p; //BiTree u=NewNode(); BiTree u=(BiTree)malloc(sizeof(BiNode)); u->data=post[len-1]; u->left=Creat(mid,post,p); u->right=Creat(mid+p+1,post+p,len-p-1); return u;}void dfs(BiTree T,int sum){ sum+=T->data; if(!T->left&&!T->right) { if(sum<best_sum||(sum==best_sum&&T->data<best)) { best_sum=sum; best=T->data; } } if(T->left)dfs(T->left,sum); if(T->right)dfs(T->right,sum);}int main(){ while(cin>>Inorder[0]) { //ans=0; input(); BiTree root=NULL; root=Creat(Inorder,Post,cnt); best_sum=1000000000; dfs(root,0); cout<<best<<endl; } return 0;}
阅读全文
0 0
- uva548 (建树)二种方式实现 简单易懂
- 【UVA548】Tree 建树+深搜 (2/1000)
- 指针建树uva548
- 【简单向】用最简单易懂的方式实现FFT
- java中实现单例模式的几种方式,简单易懂
- 简单易懂线段树-第一步建树-脑袋蒙的来瞧瞧
- uva548 Tree +二叉树用中序和后序建树
- Uva548 Tree 【递归建树+dfs遍历树】【例题6-8】
- Javascript实现二级联动下拉框(简单易懂)
- Boyer-Moore算法--C语言实现(简单易懂)
- php实现zip压缩文件解压缩代码分享(简单易懂)
- MVP 模式简单易懂的介绍方式
- MVP 模式简单易懂的介绍方式
- MVP 模式简单易懂的介绍方式
- MVP 模式简单易懂的介绍方式
- MVP 模式简单易懂的介绍方式
- MVP 模式简单易懂的介绍方式
- MVP 模式简单易懂的介绍方式
- Kafka的Producer和Consumer的示例(使用java语言)
- Hadoop入门之Mapreduce过程的几个Demo
- 坚持#第189天~练字完毕
- JavaScript中的递归函数
- kNN代码
- uva548 (建树)二种方式实现 简单易懂
- jQuery的学习日记
- ios之UILabel显示不同的颜色字体
- Android.mk文件解读
- fread读优
- 观察者模式
- 接口
- Android——对话框、通知
- Leetcode每日一练习