P3378 【模板】堆(code)

#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
int read() {
	int re = 0 , sig = 1;
	char c = getchar();
	while(c < '0' || c > '9') {
		if(c == '-')sig = -1;
		c = getchar();
	}
	while(c >= '0' && c <= '9')
		re = (re << 1) + (re << 3) + c - '0',
		c = getchar();
	return re * sig;
}

void swap_(int &a , int &b) {
	int tmp = a;	a = b;	b = tmp;
}
struct pri_que {
	int a[1000010] , siz;
	void clear() {
		memset(a , 0 , sizeof(a));
		siz = 0;
	}
	void push(int dat) {
		a[++siz] = dat;
		int p = siz;
		while(p > 0)
			if(a[p] < a[p / 2]) {
				swap_(a[p] , a[p / 2]);
				p /= 2;
			}
			else
				return;
	}
	void pop() {
		int p = 1;
		a[p] = a[siz];
		siz--;
		while(p <= siz) {
			int u ;
			if(p * 2 + 1 <= siz)
				u = a[p * 2] < a[p * 2 + 1] ? p * 2 : p * 2 + 1;
			else
				u = p * 2;
			if(u > siz)return;
			if(a[p] < a[u])return;
			swap_(a[p] , a[u]);
			p = u;
		}
	}
	int top() {
		return a[1];
	}
}q;
int main() {
	int n = read();
	for(int i = 1 ; i <= n ; i++) {
		int op = read();
		switch(op) {
			case 1 :
				q.push(read());
				break;
			case 2 :
				printf("%d\n" , q.top());
				break;
			case 3 :
				q.pop();
				break;
			break;
		}
//		cout << "====\n";
//		cout << q.siz << endl;
	}
	return 0;
}
posted @ 2020-11-23 20:28  追梦人1024  阅读(76)  评论(0编辑  收藏  举报