洛谷 P3378 【模板】堆

题目链接

https://www.luogu.org/problem/P3378

分析

堆模板,手写结构体感觉不错;移动元素位置后返回该元素最终位置,在Dijkstra算法中可支持动态修改堆中元素。

AC代码

#include 
#include 
#include 

using namespace std;

inline int read() {
	int num = 0;
	char c = getchar();
	while (c < '0' || c > '9') c = getchar();
	while (c >= '0' && c <= '9')
		num = num * 10 + c - '0', c = getchar();
	return num;
}

const int maxn = 1e6 + 5;

struct Heap {
	int h[maxn], tot;

	Heap() {
		memset(h, 0, sizeof(h));
		tot = 0;
	}

	void up(int p) {
		while (p > 1) {
			if (h[p] < h[p / 2]) swap(h[p], h[p / 2]), p /= 2;
			else break;
		}
	}

	void down(int p) {
		while (2 * p <= tot) {
			int q = 2 * p;
			if (q + 1 <= tot && h[q + 1] < h[q]) ++q;
			if (h[q] < h[p]) swap(h[q], h[p]), p = q;
			else break;
		}
	}

	void insert(int x) {
		h[++tot] = x;
		up(tot);
	}

	int get_top() {
		return h[1];
	}

	void remove(int p = 1) {
		h[p] = h[tot--];
		up(p), down(p);
	}
} h;

int main() {
	int n = read();
	for (int i = 1; i <= n; ++i) {
		int op = read();
		if (op == 1) h.insert(read());
		else if (op == 2) printf("%d\n", h.get_top());
		else if (op == 3) h.remove();
	}
	return 0;
}

你可能感兴趣的:(数据结构,题解)