求集合K中权值最小的两个元素,使用堆数据结构。O(logn)。绕过对堆的实现。使用标准模板库中的--优先队列。
#include<queue> using namespace std;
priority_queue<int> Q; //建立的是最大堆; priority_queue<int,vector<int>,greater<int>> Q; //建立的是最小堆;
将元素x放入堆中:Q.push(x);
取出堆顶元素:int a = Q.top();
弹出堆顶元素:Q.pop();
#include<queue>
#include<stdio.h>
using namespace std;
priority_queue<int,vector<int>,greater<int> > Q;
int main()
{
int n;
while(scanf("%d",&n)!=EOF)
{
while(Q.empty()==false)
Q.pop(); //清空Q中的元素
for(int i=1;i<=n;i++)
{
int x;
scanf("%d",&x);
Q.push(x);
}
int ans = 0;
while(Q.size()>1){
int a = Q.top();
Q.pop();
int b = Q.top();
Q.pop();
ans += a + b;
Q.push(a+b);
}
printf("%d\n",ans);
}
return 0;
}

浙公网安备 33010602011771号