|
| 1 | +```java |
| 2 | +import java.awt.Point; |
| 3 | +import java.io.BufferedReader; |
| 4 | +import java.io.IOException; |
| 5 | +import java.io.InputStreamReader; |
| 6 | +import java.util.*; |
| 7 | + |
| 8 | +public class Main { |
| 9 | + |
| 10 | + static int depth,leafCnt; |
| 11 | + static int [] edges,maxSum,dp; |
| 12 | + |
| 13 | + |
| 14 | + static int ans; |
| 15 | + |
| 16 | + public static void main(String[] args) throws IOException { |
| 17 | + init(); |
| 18 | + process(); |
| 19 | + print(); |
| 20 | + } |
| 21 | + |
| 22 | + private static void init() throws IOException { |
| 23 | + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); |
| 24 | + depth = Integer.parseInt(br.readLine()); |
| 25 | + leafCnt = 1 << depth; |
| 26 | + ans = 0; |
| 27 | + edges = new int [leafCnt*2]; |
| 28 | + maxSum = new int [leafCnt*2]; //maxSum: 자신부터 리프노드까지의 가중치 합 중 최댓값 |
| 29 | + dp = new int[leafCnt*2]; // 1번노드부터 i번노드까지 왔을 때 가중치 합의 최대치 |
| 30 | + |
| 31 | + //edge[i] -> i/2번 노드에서 i번 노드로 오는데 드는 가중치 |
| 32 | + // 노드가 1번부터 시작하기에 엣지 0,1번은 없다. |
| 33 | + StringTokenizer st = new StringTokenizer(br.readLine()); |
| 34 | + for (int i = 2; i < edges.length; i++) { |
| 35 | + edges[i] = Integer.parseInt(st.nextToken()); |
| 36 | + } |
| 37 | + } |
| 38 | + |
| 39 | + private static void process() throws IOException { |
| 40 | + makeMaxSumArr(1); |
| 41 | + |
| 42 | + int totalMaxSum = maxSum[1]; |
| 43 | + |
| 44 | + for (int i = 2; i < edges.length; i++) { |
| 45 | + int curSum = dp[i/2] + edges[i]; |
| 46 | + int goal = totalMaxSum - maxSum[i]; |
| 47 | + |
| 48 | + edges[i] += goal - curSum; |
| 49 | + dp[i] = dp[i/2] + edges[i]; |
| 50 | + } |
| 51 | + |
| 52 | + for (int i = 2; i < edges.length; i++) { |
| 53 | + ans += edges[i]; |
| 54 | + } |
| 55 | + |
| 56 | + } |
| 57 | + |
| 58 | + private static int makeMaxSumArr(int nodeNum) { |
| 59 | + if (nodeNum *2 >= edges.length) return maxSum[nodeNum];// == 0 |
| 60 | + int left = makeMaxSumArr(nodeNum*2) + edges[2*nodeNum]; |
| 61 | + int right = makeMaxSumArr(2*nodeNum+1) +edges[2*nodeNum+1]; |
| 62 | + |
| 63 | + return maxSum[nodeNum] = + Math.max(left, right); |
| 64 | + } |
| 65 | + |
| 66 | + |
| 67 | + private static void print() { |
| 68 | + System.out.println(ans); |
| 69 | + } |
| 70 | +} |
| 71 | + |
| 72 | + |
| 73 | +``` |
0 commit comments