codeforces 526B

因为是完全二叉树,根据题意可以知道,任何一颗子树,从根往左边走和从根往右边走经过的灯是一样多的

所以可以从下往上递推,

#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<cmath>
#include<vector>
#include<queue>
#include<iostream>
#include<iomanip>
#include<algorithm>
using namespace std;
typedef long long LL;
const int MX=200000+5;

int W[MX],n,ans=0;

int solve(int rt,int depth){
    if(depth>=n) return 0;

    int L=solve(rt<<1,depth+1)+W[rt<<1];
    int R=solve(rt<<1|1,depth+1)+W[rt<<1|1];

    ans+=abs(L-R);
    return max(L,R);
}

int main(){
    scanf("%d",&n);
    for(int i=2;i<=(1<<(n+1))-1;i++){
        scanf("%d",&W[i]);
    }

    solve(1,0);
    printf("%d\n",ans);
    return 0;
}

 

posted @ 2015-04-10 13:09  逍遥丶綦  阅读(100)  评论(0)    收藏  举报