ALDS1_9_C:Priority Queue

题目链接:http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=ALDS1_9_C

结合上一题的最大堆,实现优先队列的功能:

insert:插入元素

extract:就是pop出顶端元素,即返回当前的最大元素并且删除它的功能。

 

插入:把元素往最后插,然后向上层遍历,寻找到正确的位置为止。(因为假设当前的堆已经是最大堆)

删除:把A[1]的元素pop,然后删除的过程就是把最后一个元素放到第一个,然后对顶端元素执行max_heap操作,就保证了顶端元素的正确,而且把最后一个元素的位置也找到了。

 

代码如下:

#include <cstdio>
#include <iostream>
#include <algorithm>
#include <cstring>
using namespace std;
#define infinity (1<<30)
const int maxx=2000100;
int A[maxx];
int n;

void max_heap(int i){
	int left=2*i,right=2*i+1,x;
	if(left<=n && A[left]>A[i]) x=left;
	else x=i;
	if(right<=n && A[right]>A[x] ) x=right;
	if(x!=i){
		swap(A[x],A[i]);
		max_heap(x);
	}
	return ;
}

int extract(){
	int x;
	x=A[1];
	A[1]=A[n];
	n--;
	max_heap(1);
	return x;
}

int main (){
	string s;
	int a;
	n=0;
	while(cin>>s){
		if(s[0]=='i'){
			cin>>A[++n];
			int i=n;
			while(i>1 && A[i]>A[i/2]){
				swap(A[i],A[i/2]);
				i=i/2;
			}
		}
		else if(s[1]=='x'){
			cout<<extract()<<endl;
		}
		else return 0;
	}
	return 0;
}

错点:

1.这题对时间复杂度有一定要求,插入随便插,extract的时候再执行全堆的max_heap会TLE;

2.插入过程中i的值要注意+1的地方;

 

用STL中的priority_queue来实现

代码如下:

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <queue>
#include <cstring>
using namespace std;

int main (){
	priority_queue<int> A;
	string s;
	int a;
	while(cin>>s){
		if(s[0]=='i') {
			cin>>a;
			A.push(a);
		}
		else if(s[1]=='x'){
			a=A.top();
			A.pop();
			cout<<a<<endl;
		}
		else return 0;
	}
	return 0;
}

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值