堆模板

一些堆的总结

1.二叉堆
这个是最简单的堆,用于维护最大最小值。支持删除,弹出堆顶节点,查询最大值(或优先级最高的节点)

#include<cstdio>
#include<algorithm>
using namespace std;
const int MAXN = 1000001;

struct Node{
	int Val;
	bool operator < (const Node &a) const {
		return Val > a.Val; //重载小于号 
	}
}h[MAXN];

struct Binary_Heap{
	int HeapSize;
	inline void push(int v){
		int u = ++HeapSize, fa; h[HeapSize].Val = v;
		while(u > 1){
			fa = u >> 1;
			if(h[u] < h[fa]) break; //该节点优先级小于其父亲
			swap(h[u], h[fa]);
			u = fa; 
		}
	}
	inline int top(){
		return h[1].Val;
	}
	inline void pop(){
		int u = 1; h[1] = h[HeapSize--];
		while((u << 1) <= HeapSize){
			int Son = u << 1;
			if(Son + 1 <= HeapSize && h[Son] < h[Son + 1]) Son++;
			if(h[Son] < h[u]) break;
			swap(h[u], h[Son]);
			u = Son;
		}
	}
}Heap;

2.优先队列
这个是STL里的东西,众所周知,STL模板常数大但泛用,好写
上面的代码就可以变成这个:

#include<queue>
#include<algorithm>
using namespace std;

struct Node{
	int Val;
	bool operator < (const Node &a) const {
		return Val > a.Val; //重载小于号 
	}
};

priority_queue <Node> Heap;

3.左偏树/EX并查集(大雾
左偏树在一般的二叉堆基础之上,还支持合并操作。
配合luogu3377 【模板】左偏树(可并堆)食用

#include<cstdio>
#include<algorithm>
using namespace std;
const int MAXN = 1000001;

int val[MAXN], fa[MAXN], ch[MAXN][2], dis[MAXN];
struct Leftist_Tree{
	int Merge(int x, int y){
		if(!x || !y) return x + y;
		if(val[x] > val[y]) swap(x, y);
		else if(val[x] == val[y] && x > y) swap(x, y);
		ch[x][1] = Merge(ch[x][1], y); fa[ch[x][1]] = x;
		if(dis[ch[x][0]] < dis[ch[x][1]]) swap(ch[x][0], ch[x][1]);
		dis[x] = dis[ch[x][1]] + 1;
		return x;
	}
	inline int top(int t){
		while(fa[t]) t = fa[t];
		return t;
	}
	inline void pop(int t){
		val[t] = -1;
		fa[ch[t][0]] = fa[ch[t][1]] = 0;
		Merge(ch[t][0], ch[t][1]);
	}
}Heap;

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

int main(){
	int n = read(), m = read();
	for(int i = 1; i <= n; i++) val[i] = read();
	for(int i = 1; i <= m; i++){
		int opt = read(), x, y;
		if(opt == 1){
			x = read(), y = read();
			if(val[x] == -1 || val[y] == -1) continue;
			x = Heap.top(x), y = Heap.top(y);
			if(x == y) continue;
			Heap.Merge(x, y);
		}
		else{
			x = read();
			if(val[x] == -1){printf("-1\n"); continue;}
			x = Heap.top(x);
			printf("%d\n", val[x]);
			Heap.pop(x);
		}
	}
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值