uva 699 The Falling Leaves

//思路:一遍输入扩展前序一遍建树,在建树过程中记录该结点的水平坐标,根结点的坐标为0,往左减1,往右加1,最后会的到一个最左侧坐标L,最右侧坐标R

建树之后见遍历、,遍历过程中,统计各个坐标的值并求他们的和保存在数组中,但是左侧的坐标是负值,数组没有负值,所以开一个二维数组sum[2][MAX],第一行对应右侧的坐标,从1到R,第二行对应左侧的坐标,从1到-L,也就是将左侧的坐标在统计时取绝对值,然后累加求和.思考可知建树和遍历的过程实际上相同所以干脆把遍历去掉,直接建树,建树过程中就求水平坐标并累计求和

 

//注意输出的格式,时间也不太好,0.100上下

 

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define LEN sizeof(struct BTree)
#define MAX 10010
int sum[2][MAX];
int L,R;
struct BTree
{
    int data,pos;
    struct BTree *lchild,*rchild;
}*pre;  //建树时记录前驱结点


void create_BTree(struct BTree* *T , int mark)
{
    int a,k;
    scanf("%d",&a);
    if(a==-1) {(*T)=NULL; return ;}
    else
    {
        (*T)=(struct BTree*)malloc(LEN); (*T)->data=a;
        if(mark==1)            (*T)->pos=pre->pos-1; 
        else if(mark==2)        (*T)->pos=pre->pos+1;
        else                    (*T)->pos=0;
        if((*T)->pos>=0)
        {
            k=(*T)->pos; sum[0][k]+=(*T)->data;
            if((*T)->pos>R) R=(*T)->pos;
        }
        else
        {
            k=0-(*T)->pos; sum[1][k]+=(*T)->data;
            if((*T)->pos<L)        L=(*T)->pos;
        }
        pre=(*T); mark=1; create_BTree( &((*T)->lchild) , mark);
        pre=(*T); mark=2; create_BTree( &((*T)->rchild) , mark);
    }
}
int main()
{
    struct BTree *T;  int N=0,i,mark,flag;  
    while(1)
    {
        memset( sum,0,sizeof(sum) );
        mark=0; pre=NULL; L=R=0; create_BTree(&T,mark);
        if(!T)  return 0;
        N++;  printf("Case %d:\n",N);
//        printf("L=%d   R=%d\n",L,R);
        flag=0;  //为了服务于输出格式而存在的
        for(i=0-L; i>0; i--)    
        {
            if(!flag) { flag=1; printf("%d",sum[1][i]);}
            else      printf(" %d",sum[1][i]);
        }
        if(!flag)    printf("%d",sum[0][0]);  else printf(" %d",sum[0][0]);
        for(i=1; i<=R; i++)        printf(" %d",sum[0][i]); 
        printf("\n\n");
    }
    return 0;
}

 

原文地址:https://www.cnblogs.com/scau20110726/p/2712635.html