跳到正文

个人记录

对顶堆

Zhenggeek约 2 分钟
原文
文章信息与版本

文章信息

收录
2026年4月4日
更新
2026年5月2日
篇幅
约 2 分钟

版本

  1. v1当前
C++
void balance(priority_queue<int> &max_heap,priority_queue<int,vector<int> , greater<int> > &min_heap, int &sum_min,int &sum_max,int size){
	while(max_heap.size() > size){
		int val = max_heap.top();max_heap.pop();
		sum_max -= val;
		sum_min += val;
		min_heap.push(val);
	}
	while(max_heap.size() < size){
		if(min_heap.empty())  break;
		int val = min_heap.top();min_heap.pop();
		sum_min -= val;
		sum_max += val;
		max_heap.push(val);
	}
	while(max_heap.size() && min_heap.size() && max_heap.top() > min_heap.top()){
		int a = max_heap.top();max_heap.pop();
		int b = min_heap.top();min_heap.pop();
		sum_max -= a;
		sum_min += a;
		sum_max -= b;
		sum_min += b;
		max_heap.push(b);
		min_heap.push(a);
	}
}
void insert(priority_queue<int> &max_heap, priority_queue<int, vector<int> , greater<int> > &min_heap,int &sum_max,int &sum_min,int x){
	if(max_heap.empty() || x <= max_heap.top()){
		max_heap.push(x);
		sum_max += x;
	}
	else{
		min_heap.push(x);
		sum_min += x;
	}
}
原文