669:The Falling Leaves

The Falling Leaves

这道题还是递归,仿照上道题的思路挺容易的,不过看了看书上的代码个人觉得我的代码更简洁,思路更清晰些哈哈。

我的思路:开个负下标数组,记录每个位置的权重之和,用 p 记录当前节点位置,那么其左节点位置为 p - 1,右节点位置为 p + 1,依次递归增加相应位置的权重,同时更新最右和最左边位置。

#include<bits/stdc++.h>
using namespace std;
const int maxn = 10000 + 5;
int _[maxn*2];
int *cnts = _ + maxn; //负下标数组 指针位于中间
int pl,pr;
void solve(int p,int n){
    if(p > pr) pr = p;
    if(p < pl) pl = p;
    cnts[p] += n;
    scanf("%d",&n);
    if(n != -1) solve(p-1,n);
    scanf("%d",&n);
    if(n != -1) solve(p+1,n);
}
int main(){
    // freopen("data.in","r",stdin);
    // freopen("data.out","w",stdout);
    int p,n,t = 0;
    while(scanf("%d",&n) && n != -1){
        p = 0;
        pl = maxn; pr = -maxn;
        memset(_,0,sizeof(_));
        solve(p,n);
        printf("Case %d:\n",++t);
        for(int i = pl;i < pr;i++) printf("%d ",cnts[i]);
        printf("%d\n\n",cnts[pr]);
    }
    return 0;
}

posted @ 2018-05-31 13:26  ACLJW  阅读(114)  评论(0编辑  收藏  举报