Comments

In brief, let f be the position of my friend. If f!=n, use then n must be bribed. Since 1) n can win [n/2+1, n] and become the top while [n/2, n-1] each has a sure win in the segment of [n/4+1,n/2], then we find the cheapest in [n/2, n-1] to bribe to win [n/4+1,n/2] for our friend f — throw out the one bribed. Then consider [n/8+1,n/4] segment in a similar way, bribe the cheapest one in [n/4, n-2] until we have covered everyone stronger than f.

The code is as follows.

include<bits/stdc++.h>

using namespace std;

using ll=long long; // #define _debug

vector a; int s, t, n, f, r; ll cost = 0; vector h;

struct greaters{ bool operator()(const int& a,const int& b) const{ return a>b; } };

int main(){

ifdef _debug freopen("cfinput.txt", "r", stdin); freopen("cfoutput.txt", "w", stdout);

endif

cin >> n; 
a.resize(n + 2); 
h.resize(n + 2);

for (int i = 1; i <= n; i++) {
    cin >> a[i];
    if (a[i] == -1) f = i; 
}

s = n; 
t = n + 1; 

r = n - f; 

while (r > 0){
    make_heap(begin(a) + s, begin(a) + t, greaters()); 
    //cout << a[s] << endl; 
    cost += a[s];
    t--; 
    a[s] = a[t];
    n /= 2;
    s -= n; 
    r -= n; 
}
cout << cost; 

}