Rick's Blog

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

求集合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;
}

 

 

posted on 2014-04-07 14:50  rick-hsg  阅读(147)  评论(0编辑  收藏  举报