合并果子

来源:互联网 发布:熊猫看书软件下载 编辑:程序博客网 时间:2024/06/05 16:20
#include<iostream>
#include <algorithm>
using namespace std;


int n;
int a[10001];
int size;
int h[10001];




void put(int x)
{
h[++size]=x;
int end,mid;
end=size;
while(end>1)
{
mid=end/2;
if(h[end]>=h[mid])
return ;
swap(h[end],h[mid]);
end=mid;


}


int get()
{
int res=h[1];
h[1]=h[size];
size--;

int front,next;
front=1;
while(front*2<=size)
{
next=front*2;
if(next<size&&h[next+1]<h[next])
next++;

if(h[front]<=h[next])
return res;

swap(h[front],h[next]);
front=next;
}



return res;

}




int main()
{
int ans=0;

cin>>n;
for(int i=1;i<=n;i++)
{
int x;
cin>>x;
put(x);

}
for(int i=1;i<n;i++)
{
int x=get();
int y=get();
ans+=x+y;
put(x+y);

}

cout<<ans;

return 0;
}