#include<bits/stdc++.h>
using namespace std;
int head_size,n;
int heap[601000];
void put(int d)
{
    int now,next;
    heap[++head_size]=d;
    now=head_size;
    while(now>1)
    {
        next=now>>1;
        if(heap[now]>=heap[next])return ;
        swap(heap[now],heap[next]);
        now=next;
    }
}
int get()
{
    int now,next,res;
    res=heap[1];
    heap[1]=heap[head_size--];
    now=1;
    while(now*2<=head_size)
    {
        next=now*2;
        if(next<head_size&&heap[next+1]<heap[next])
            next++;
        if(heap[now]<heap[next])return res;
        swap(heap[now],heap[next]);
        now=next;
    }
    return res;
}
void work()
{
    int x,y,ans=0;
    scanf("%d",&n);
    for(int i=1;i<=n;i++){
        scanf("%d",&x);
        put(x);
    }
    for(int i=1;i<n;i++){
        x=get();
        y=get();
        ans+=x+y;
        put(x+y);
    }
    printf("%d\n",ans);
}
int main()
{
    work();
    return 0;
}
View Code

猜你喜欢

转载自www.cnblogs.com/kgxw0430/p/9005042.html