uva 548 - Tree

大意:给定前序和后序遍历,先找出从根到叶sum最小的路径,然后输出叶子上的值,如果有多条路径满足,输出值最小的。
做法:
算法入门经典p106有详细介绍,当然根据是否建树,也有两种做法:
做法一:
#include<iostream>

#include<cstdio>

#include<cstring>

#include<cctype>

#include<cstdlib>

using namespace std;

char s[100005];

int v1[100005],v2[100005],top;

int min_sum,ans;

int init(char *s,int *v)

{

    int top=0;

    for(int i=0;s[i];i++)

    {

        while(s[i]==' ')

        i++;

        v[top]=0;

        while(s[i]&&isdigit(s[i]))

        {

            v[top]=v[top]*10+s[i]-'0';

            i++;

        }

        top++;

        if(!s[i]) break;

    }

    return top;

}

int find(int *v,int n,int c)

{

    for(int i=n-1;i>=0;i--)

    if(v[i]==c)

    return i;

    return 0;

}

void build(int n,int *v1,int *v2,int sum)

{

    if(n<=0)

    return ;



    int p=find(v1,n,v2[n-1]);



    sum+=v2[n-1];



    if(p<=0&&n-p-1<=0)

    {

        if(sum==min_sum)

        ans=min(ans,v2[n-1]);

        else if(sum<min_sum)

        {

            min_sum=sum;

            ans=v2[n-1];

        }

        return ;

    }



    build(p,v1,v2,sum);

    build(n-p-1,v1+p+1,v2+p,sum);

}



int main()

{

    while(gets(s))

    {

        int v;

        init(s,v1);

        gets(s);

        top=init(s,v2);



        ans=min_sum=10000000;

        build(top,v1,v2,0);



        printf("%d\n",ans);

    }

    return 0;

}

 做法二:

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cctype>
#include<cstdlib>
using namespace std;
struct node
{
struct node *left;
struct node *right;
int v;
};
node *root;
char s[100005];
int v1[100005],v2[100005],top;
int init(char *s,int *v)
{
int top=0;
for(int i=0;s[i];i++)
{
while(s[i]=='')
i++;
v[top]=0;
while(s[i]&&isdigit(s[i]))
{
v[top]=v[top]*10+s[i]-'0';
i++;
}
top++;
if(!s[i]) break;
}
return top;
}
int find(int *v,int n,int c)
{
for(int i=n-1;i>=0;i--)
if(v[i]==c)
return i;
return 0;
}
node *build(int n,int *v1,int *v2)
{
if(n<=0)
return NULL;

int p=find(v1,n,v2[n-1]);

node *root=(node *)malloc(sizeof(node));
root->v=v2[n-1];

root->left=build(p,v1,v2);
root->right=build(n-p-1,v1+p+1,v2+p);

return root;
}
int min_sum,ans;

void dfs(node *root,int sum)
{
if(root==NULL)
return ;
sum+=root->v;
if(root->left==NULL&&root->right==NULL)
{
if(min_sum>sum)
{
min_sum=sum;
ans=root->v;
}
else if(min_sum==sum)
ans=min(ans,root->v);

return;
}
dfs(root->left,sum);
dfs(root->right,sum);
}
int main()
{
while(gets(s))
{
int v;
init(s,v1);
gets(s);
top=init(s,v2);

node *root;
root=build(top,v1,v2);

ans=min_sum=10000000;
dfs(root,0);
printf("%d\n",ans);
}
return 0;
}

 

你可能感兴趣的:(tree)