题解 P1090 【合并果子】
狂奔的麻花疼
·
·
题解
这道题可以用双队列+贪心来做,也可以用二叉堆,这里我选用二叉堆
#include<iostream>
#include<cstdio>
using namespace std;
int k,m,n,tot=0,heap[30001],size;
void change(int &a,int &b)
{
int t=a;
a=b;
b=t;
}
void put(int x)
{
int pre,post;
heap[++size]=x;
pre=size;
while(pre>1)
{
post=pre/2;
if (heap[post]<=heap[pre])
return ;
change(heap[post],heap[pre]);
pre=post;
}
}
int get()
{
int pre,post,res;
res=heap[1];
heap[1]=heap[size--];
pre=1;
while (pre*2<=size)
{
post=pre*2;
if (post<size&&heap[post+1]<heap[post])
post++;
if (heap[pre]<=heap[post])
return res;
change(heap[pre],heap[post]);
pre=post;
}
return res;
}
int main()
{
cin>>n;
for (int i=1;i<=n;i++)
{
cin>>k;
put(k);
}
for (int i=1;i<n;i++)
{
k=get();
m=get();
tot+=k+m;
put(k+m);
}
cout<<tot;
return 0;
}