目录
一、题目链接:https://www.luogu.com.cn/problem/P1090
一、题目链接:https://www.luogu.com.cn/problem/P1090
标签:贪心,二叉堆,优先队列
二、思路:
最开始的思路:利用 sort() 将最小的两个果子堆合并,然后再次排序,不断重复直到只剩一堆。
缺点:时间复杂度难以想象地高
正确思路:利用堆里面的优先队列对果子堆进行操作,从而达到不用进行一个大的排序从而获得最小的两个数的效果。
在默认情况下,数值越小的优先级越低,放入-x从而达到数值越小的数优先级越高,省去了自定义仿函数的操作。
三、AC代码:
#include<iostream>
#include<queue>
using namespace std;
priority_queue<int>q;
int main()
{
int n,x,i,t,ans=0;
cin>>n;
for(i=0;i<n;++i)
{
cin>>x;
q.push(-x);
}
while(--n)
{
t=0;
t-=q.top(); q.pop();
t-=q.top(); q.pop();
ans+=t;
q.push(-t);
}
cout<<ans<<endl;
return 0;
}
拓展1:
top()是取出栈顶元素,不会删掉栈里边的元素
pop()是删除栈顶元素