现在的位置: 首页 > 综合 > 正文

2019年02月20日 ⁄ 综合 ⁄ 共 1078字 ⁄ 字号 评论关闭
#include<cstdio>
#include<cstring>
#include<iostream>
#include<queue>
#include<algorithm>
using namespace std;
#define maxn 1000
struct heap
{
	int element[maxn];
	int n;
};
heap h;
void insert(int x)
{
	if(h.n!=maxn-1){
		int i=++h.n;
		while(i!=1&&x>h.element[i/2])
			h.element[i]=h.element[i/2],i/=2;
		h.element[i]=x;
	}
}
int Delemax()
{
	if(h.n==0)return -1;
	int tmp=h.element[h.n--];
	int ans=h.element[1];
	int child=2,parent=1;
	while(child<=h.n){
		if(child<h.n&&h.element[child]<h.element[child+1])
			child++;
		if(tmp>=h.element[child])break;
		h.element[parent]=h.element[child];
		parent=child;
		child*=2;
	}
	h.element[parent]=tmp;
	return ans;
}
void Bfs()
{
	queue<int> q;
	while(!q.empty())q.pop();
	if(h.n==0)return;
	q.push(1);
	int n=h.n;
	while(!q.empty()){
		int tmp=q.front();
		q.pop();
		if(tmp*2<=h.n&&h.element[tmp*2]!=0)q.push(tmp*2);
		if(tmp*2+1<=h.n&&h.element[tmp*2+1]!=0)q.push(tmp*2+1);
		printf("%d ",h.element[tmp]);
	}
	puts("");
	return ;
}
int main()
{
	memset(h.element,0,sizeof(h.element));
	h.n=0;
	int chos;
	while(true){
		scanf("%d",&chos);
		if(!chos)break;
		if(chos==1){
			int x;
			scanf("%d",&x);
			insert(x);
		}
		else if(chos==2){
			printf("%d\n",Delemax());
			Bfs();
		}
		else{
			Bfs();
		}
	}
	return 0;
}

堆的插入删除

抱歉!评论已关闭.