堆(heap)

堆(heap)

push:插入一个元素,O(logn)
top:返回当前元素最小值,O(1)
pop:将当前最小元素弹出队列,O(logn)

代码:

#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>

#define rep(i,x,y) for (int i=x;i<=y;i++)
#define dep(i,y,x) for (int i=y;i>=x;i--)

using namespace std;

const int maxn=100000+10,INF=(1<<30);

int a[maxn],heap[maxn],n,x,k,size,type;

void init()
{
 rep(i,1,maxn-1) heap[i]=INF;
 size=0;
}

void push(int x)
{
 size++,k=size,heap[k]=x;

 while ((k>1)&&(heap[k]<heap[k>>1]))
 {
  swap(heap[k>>1],heap[k]);
  k>>=1;
 }
}

int top() {return heap[1];}

void pop()
{
 swap(heap[1],heap[size]);
 heap[size]=INF;

 size--,k=1;

 while ((k<<1)<=size)
 {
  if ((heap[k]<=heap[(k<<1)])&&(heap[k]<=heap[(k<<1)+1])) break;
  if (heap[(k<<1)]<heap[(k<<1)+1]) 
    swap(heap[(k<<1)],heap[k]),k<<=1; 
  else 
    swap(heap[(k<<1)+1],heap[k]),k=(k<<1)+1;
 }
}

int main()
{
 scanf("%d",&n);
 
 init();

 rep(i,1,n)
 {
  scanf("%d",&a[i]);
  push(a[i]);
 }

 while (scanf("%d",&type)==1)
 {
  if (type==1) 
  {
   scanf("%d",&x);
   push(x);
  }

  if (type==2) printf("- %d\n",top());
  if (type==3) pop();
 }

 return 0;
}

posted @ 2016-08-27 19:29  Krew  阅读(180)  评论(0)    收藏  举报