1. 程式人生 > >堆【模版】

堆【模版】

堆【模版】

洛谷(p3378)

這裡以小根堆為例

插入一個元素

void insert(int x)
{
	heap[++siz] = x;
	int pos = siz;
	while(pos != 1)
	{
		if(heap[pos] >= heap[pos/2])break;
		swap(heap[pos],heap[pos/2]);
		pos /= 2;
	}
	return ;
}

刪除堆頂元素

int del()
{
	heap[1] = heap[siz];
	siz --;
	int pos = 1;
	while(pos * 2 <=
siz) { int to = pos * 2; if((pos*2+1<=siz) && (heap[pos*2+1] <heap[pos*2])) to = pos * 2 + 1; if(heap[pos] > heap[to])swap(heap[pos],heap[to]); else break; pos = to; } return 0; }

綜合起來的程式碼如下

#include<iostream>
#include<cstdio>

using namespace std;

int
heap[1000005],k,z,n,siz; void insert(int x) { heap[++siz] = x; int pos = siz; while(pos != 1) { if(heap[pos] >= heap[pos/2])break; swap(heap[pos],heap[pos/2]); pos /= 2; } return ; } int del() { heap[1] = heap[siz]; siz --; int pos = 1; while
(pos * 2 <= siz) { int to = pos * 2; if((pos*2+1<=siz) && (heap[pos*2+1] <heap[pos*2])) to = pos * 2 + 1; if(heap[pos] > heap[to])swap(heap[pos],heap[to]); else break; pos = to; } return 0; } int main() { scanf("%d",&n); while(n --) { scanf("%d",&k); if(k == 1) { scanf("%d",&z); insert(z); } if(k == 2) { printf("%d\n",heap[1]); } if(k == 3) { del(); } } return 0; }

P.S. 如果你覺得這個太難看不懂,這有簡單的——優先佇列