uva548 Tree

题意:给一个树中缀,和后缀序列,求这个树叶子到根的最小路径和,如果有多条,输出叶子最小的那条。

思路:先根据给的中缀,后缀序列,递归重建树,思路就是后缀序列的最后一个就是目前这个树的根,也是吧中序序列分成两半,一边是左子树,一边是右子树,同理依次往前 找每个子树的根节点。


至于建树,这个很关键,由于这题每个点都不重复,并且点只有10000个,可以对应权值就是那个点号码,用数组l,r记录每个点的左右子孙是,叶子节点就是0。用数组建树,方便不容易蹦,当然用链表也是可以的。


#include
#include
#include
#include
#include
using namespace std;
const int maxn=11000;
const int inf=0x7fffffff;
int pre_order[maxn],in_order[maxn],post_order[maxn],l[maxn],r[maxn],best_sum,best,n;
bool read_input(int *a)
{
    string s;
    if(!getline(cin,s)) return false;
    stringstream str(s);
    n=0;int x;
    while(str>>x) a[n++]=x;
    return n>0;
}

int bulid(int l1,int r1,int l2,int r2)
{
    if(l1>r1) return 0;
    int root=post_order[r2];
    int p=l1;
    while(in_order[p]!=root) p++;
    int cnt=p-l1;;
    l[root]=bulid(l1,p-1,l2,l2+cnt-1);
    r[root]=bulid(p+1,r1,l2+cnt,r2-1);
    return root;
}

void dfs(int cur,int sum)
{
    sum+=cur;
    if(!l[cur]&&!r[cur]){
        if(sum
链表写树

#include
#include
#include
#include
#include
using namespace std;
struct Node{
   int v;
   Node *left,*right;
};
Node *root;
Node *newnode() {return new Node();}
const int inf=0x7fffffff;
const int maxn=10000+10;
int post_order[maxn],in_order[maxn],n,ok,best_sum,best;

bool read_input(int *a)
{
    string s;
    if(!getline(cin,s)) return false;
    stringstream buff(s);
    int x;n=0;
    while(buff>>x) a[n++]=x;
    return n>0;
}

Node* bulid(int l1,int r1,int l2,int r2)
{
    if(l1>r1) return NULL;
    Node *t=newnode();
    t->v=post_order[r2];
    int p=l1;
    while(in_order[p]!=t->v) p++;
    int cnt=p-l1;
    t->left=bulid(l1,p-1,l2,l2+cnt-1);
    t->right=bulid(p+1,r1,l2+cnt,r2-1);
    return t;
}

void dfs(Node *t,int sum)
{
    sum+=t->v;
    if(!t->left&&!t->right){
        if(sumvv;
        }
    }
    if(t->left) dfs(t->left,sum);
    if(t->right) dfs(t->right,sum);
}

int main()
{
    while(read_input(in_order)){
        read_input(post_order);
        best_sum=inf;best=inf;
        root=bulid(0,n-1,0,n-1);
        dfs(root,0);
        printf("%d\n",best);
    }
}


你可能感兴趣的:(uva548 Tree)