贪心,每次选择最小的两个合并,这题的贪心策略很容易想到,一开始我采用的是每次贪心完就重新排序的方法,妥妥T了....想到了用优先队列的方法做,也算是第一次用优先队列吧,当熟悉一下了
要注意的是优先队列的less<> greater<> 如果是结构体的话要重载小于运算符
(不过虽然说是会用了优先队列...对它内部的结构原理还不是很理解,分不清堆和优先队列的不同,有空再了解一下)
如:
priority_queue <int,vector<int>,less<int> > p;//从大到小排序
priority_queue <int,vector<int>,greater<int> > q;//从小到大排序
上代码:
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<queue>
using namespace std;
int n;
const int maxn = 10000+10;
int a[maxn];
priority_queue<int,vector<int>,greater<int> >q;//从小到大排序
void Solve()
{
long long ans = 0;
while(!q.empty())
{
int temp1 = q.top();//取队首元素用的是.top()
q.pop();
if(q.empty())
{
break;
}
int temp2 = q.top();
q.pop();
ans += temp1+temp2;
//cout<<ans<<endl;
q.push(temp1+temp2);
}
cout<<ans<<endl;
}
int main()
{
while(cin>>n)
{
for(int i=0;i<n;i++)
{
cin>>a[i];
q.push(a[i]);
}
//while(!q.empty())
//printf("%d ",q.top()),q.pop();
Solve();
}
}
371

被折叠的 条评论
为什么被折叠?



