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[],right1[];
bool read1(int *a); int zhong[],hou[];
int n;int best;int max1;
int main()
{ while(read1(zhong))
{
read1(hou); built(,n-,,n-);
max1=;
dfs(hou[n-],);
printf("%d\n",best);
} return ;
}
int built(int L1,int R1,int L2,int R2)
{
if(L1>R1) return ;
int root=hou[R2];
int p=L1;
while(zhong[p]!=root)p++;
int c=p-L1; left1[root]=built(L1,p-,L2,L2+c-);
right1[root]=built(p+,R1,L2+c,R2-);
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=;
while(ss>>x)a[n++]=x;
return n>; }
上一篇:Notepad++ Shortcuts(Chinese and English Version)


下一篇:Android 上使用 iconfont 的一种便捷方案