Home BOJ. Binary Tree (13325)
Post
Cancel

BOJ. Binary Tree (13325)

[Link] https://www.acmicpc.net/problem/13325


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#include <algorithm>
#include <iostream>
#include <vector>
#include <map>
#include <set>
#include <queue>
// #include <bits/stdc++.h>
using namespace std;
#define for0(i, n) for(int i = 0; i < n; i++)
#define for1(i, n) for(int i = 1; i < n; i++)
#define fori(s, e) for(int i = s; i < e; i++)
#define endl "\n"
typedef long long ll;
const int INF = 987654321;
const int MAX = 100;

int n, m, ans = 0;
vector<int> edges;

int dfs(int idx) {
  if(idx << 1 >= (1 << n+1)) return 0;
  int dfs_left = dfs(idx << 1), dfs_right = dfs(idx << 1 | 1);
  int max_val = max(dfs_left + edges[idx << 1], dfs_right + edges[idx << 1 | 1]);
  edges[idx << 1] += max_val - (dfs_left + edges[idx << 1]);
  edges[idx << 1 | 1] += max_val - (dfs_right + edges[idx << 1 | 1]);
  return max_val;
}

int main() {
  ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
  cin >> n;
  edges.push_back(0); edges.push_back(0);
  for0(i, (1 << n+1) - 2) { int in; cin >> in; edges.push_back(in); }
  dfs(1);
  long sum = 0l;
  for0(i, 1 << n+1) sum+=edges[i];
  cout << sum;
  return 0;
}
This post is licensed under CC BY 4.0 by the author.