跳到正文

题解

P3378 【模板】堆题解

#SUSPENDED#约 3 分钟
原文
文章信息与版本

文章信息

发布
2025年7月19日
收录
2025年12月12日
更新
2026年11月11日
篇幅
约 3 分钟
题目
P3378

版本

  1. v1当前

分析

首先简单看一下这道题的题目,可以看出这是一道典型的模板题 我的做法主要有两种,第一种就是简单的建设二叉堆,然后进行操作;第二种就是直接使用优先队列priority_queue。

解法1

先声明head数组,并让数组存储每一个点,并用len来存储数组长度

C++
#include <bits/stdc++.h>
using namespace std;
int n,heap[1000005],len;
void push(int x){//进行上浮操作
	heap[++len]=x;
	int i=len;
	while(i>1 && heap[i]<heap[i/2]){//如果节点i不是根节点,并且节点i比它的父节点(i/2)要小,就将他们交换
		swap(heap[i],heap[i/2]);//交换
		i=i/2;
	}
}
void pop(){//进行下沉操作
	heap[1]=heap[len--];
	int i=1;
	while(2*i<=len){
		int son=2*i;
		if(son<len && heap[son+1]<heap[son]){//如果节点son存在并且左子节点son比右子节点son+1大的时候,就直接观察右子节点
			son++;
		}
		if(heap[son]<heap[i]){//判断是否交换
			swap(heap[son],heap[i]);
			i=son;
		}else{
			break;
		}
	}
}
int main(){
    cin>>n;
    while(n--){//简单操作
		int op;
		cin>>op;
		if(op==1){
			int x;
			cin>>x;
			push(x);
		}else if(op==2){
			cout<<heap[1]<<endl;
		}else{
			pop();
		}
	}
    return 0;
}

解法2

直接声明优先队列priority_queue,用优先队列存树

C++
#include <bits/stdc++.h>
using namespace std;
priority_queue<int,vector<int>,greater<int> > q;
int main(){
    int n;
    cin>>n;
    while(n--){
		int op;
		cin>>op;
		if(op==1){
			int x;
			cin>>x;
			q.push(x);
		}else if(op==2){
			cout<<q.top()<<endl;
		}else{
			q.pop();
		}
	}
    return 0;
}

感谢大家,这是萌新第一次写题解 ,其实是第二次,第一次被官方劝回了555…

原文