CF BUDDY
← Problems·

1260E · Tournament

2400 · brute force, dp, greedy

Problem: You are organizing a boxing tournament, where nn boxers will participate (nn is a power of 22), and your friend is one of them. All boxers have different strength from 11 to nn, and boxer ii wins in the match against boxer jj if and only if ii is stronger than jj.

The tournament will be organized as follows: nn boxers will be divided into pairs; the loser in each pair leaves the tournament, and n2\frac{n}{2} winners advance to the next stage, where they are divided into pairs again, and the winners in all pairs advance to the next stage, and so on, until only one boxer remains (who is declared the winner).

Your friend really wants to win the tournament, but he may be not the strongest boxer. To help your friend win the tournament, you may bribe his opponents: if your friend is fighting with a boxer you have bribed, your friend wins even if his strength is lower.

Furthermore, during each stage you distribute the boxers into pairs as you wish.

The boxer with strength ii can be bribed if you pay him aia_i dollars. What is the minimum number of dollars you have to spend to make your friend win the tournament, provided that you arrange the boxers into pairs during each stage as you wish?

Input Format: The first line contains one integer nn (2n2182 \le n \le 2^{18}) — the number of boxers. nn is a power of 22.

The second line contains nn integers a1a_1, a2a_2, ..., ana_n, where aia_i is the number of dollars you have to pay if you want to bribe the boxer with strength ii. Exactly one of aia_i is equal to 1-1 — it means that the boxer with strength ii is your friend. All other values are in the range [1,109][1, 10^9].

Output Format: Print one integer — the minimum number of dollars you have to pay so your friend wins.

Note: In the first test case no matter how you will distribute boxers into pairs, your friend is the strongest boxer and anyway wins the tournament.

In the second test case you can distribute boxers as follows (your friend is number 22):

1:2,8:5,7:3,6:41 : 2, 8 : 5, 7 : 3, 6 : 4 (boxers 2,8,72, 8, 7 and 66 advance to the next stage);

2:6,8:72 : 6, 8 : 7 (boxers 22 and 88 advance to the next stage, you have to bribe the boxer with strength 66);

2:82 : 8 (you have to bribe the boxer with strength 88);

Sample Cases

Case 1

Input

4
3 9 1 -1

Output

0

Case 2

Input

8
11 -1 13 19 24 7 17 5

Output

12

Similar problems

00:00:00
Loading editor…
Welcome! I'm your coding tutor for this problem. Use the chips below to reveal stored hints or get AI feedback on your code. I'll guide you step by step — never giving away the solution.

Sign in to unlock AI tutor feedback