6-8 树 uva548

read 的方式值得学习 

当不知道每一行有多少个输入的时候

getline  在弄成stringstream!一个一个处理

用built递归的方式化大为小进行建立树

dfs 遍历整个树来求最值

变量的功能要明确   当我设置了一个全局变量的时候 无意间在read函数中int n  导致局部n有值  而全局n始终为0

因此要明确变量很重要   这题很有价值  多打几遍!!!!!

#include<bits/stdc++.h>
using namespace std;
int built(int L1,int R1,int L2,int R2);
void dfs(int node,int sum);
int left1[10000],right1[10000];
 bool read1(int *a);

int zhong[10000],hou[10000];
int n;int best;int max1;
int main()
{


    while(read1(zhong))
    {
        read1(hou);

        built(0,n-1,0,n-1);
        max1=1000000000;
        dfs(hou[n-1],0);
        printf("%d\n",best);
    }










    return 0;
}
int built(int L1,int R1,int L2,int R2)
{
    if(L1>R1) return 0;
    int root=hou[R2];
    int p=L1;
    while(zhong[p]!=root)p++;
    int c=p-L1;

    left1[root]=built(L1,p-1,L2,L2+c-1);
    right1[root]=built(p+1,R1,L2+c,R2-1);
    return root;


}


void dfs(int node,int sum)
{
    sum+=node;
    if(!left1[node]&&!right1[node])
    {
        if(sum<max1||(sum==max1&&node<best)){best=node;max1=sum;}


    }
    if(left1[node])dfs(left1[node],sum);
    if(right1[node]) dfs(right1[node],sum);

}


 bool read1(int *a)
 {
     string line;
     if(!getline(cin,line))return false;

     stringstream ss(line);
     int x; n=0;
     while(ss>>x)a[n++]=x;
     return n>0;


 }
View Code

猜你喜欢

转载自www.cnblogs.com/bxd123/p/10289714.html
6-8