题目链接:http://codeforces.com/problemset/problem/526/B
题意:给出一颗满二叉树和边权,求使每颗子树的左右子树边权相同最少需要添加的权为多少
//CodeForces 526B Om Nom and Dark Park
//dp + dfs
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
using namespace std;
const int maxn = 5000;
int dp[maxn];//dp[i]表示从第i个节点到出口共有的路灯数
int a[maxn];//a[i]表示连接节点i/2 和节点i的路上的路灯数
int m, n;
int ans;//ans为增加的路灯数
//从叶子节点往上遍历
int dfs(int x)
{
if (x >= m)
return 0;
dp[x * 2] = dfs(x * 2);
dp[x * 2 + 1] = dfs(x * 2 + 1);
dp[x] = max(dp[x * 2] + a[x * 2], dp[x * 2 + 1] + a[x * 2 + 1]);//x节点的路灯数为其子节点的路灯数的大值
ans += (dp[x] - a[x * 2] - dp[x * 2]) + (dp[x] - a[x * 2 + 1] - dp[x * 2 + 1]);
return dp[x];
}
int main()
{
while (~scanf("%d", &n))
{
memset(dp, 0, sizeof(dp));
m = (int)pow(2, n + 1);
for (int i = 2; i <= m - 1; i++)
scanf("%d", &a[i]);
int p = dfs(1);
printf("%d\n", ans);
}
return 0;
}