P3378第一次尝试手写二叉堆错的五颜六色求助
  • 板块题目总版
  • 楼主damon2009
  • 当前回复1
  • 已保存回复1
  • 发布时间2023/5/20 23:12
  • 上次更新2023/10/23 15:11:15
查看原帖
P3378第一次尝试手写二叉堆错的五颜六色求助
590833
damon2009楼主2023/5/20 23:12
#include<bits/stdc++.h>
using namespace std;
const int N=2000009;
int w[N],n,tot=0;
void repairup(int m){
	if(m==1||w[m]>w[m/2]) return;
	swap(w[m],w[m/2]);
	repairup(m/2);
}
void push(int m){
	tot++;
	w[tot]=m;
	repairup(tot);
}
void repairdown(int x){
	if(x*2>tot) return;
	int tar=x*2;//x的左儿子 
	if(x*2+1<=tot) tar=(w[x*2]<w[x*2+1])?x*2:x*2+1;//tar=x左右儿子中值较小的key
	if(w[x]>w[tar]){
		swap(w[x],w[tar]);
		repairdown(tar);
	} 
}
int pop(){
	swap(w[1],w[tot]);
	tot--;
	repairdown(1);
} 
int main(){
	//freopen("P3378_1.in","r",stdin);
	cin>>n;
	for(int i=1;i<=n;i++){
		int op,m;
		cin>>op;
		if(op==1){
			//cout<<"push"<<endl;
			cin>>m;
			push(m);//将元素m插入小根堆 
		}
		else if(op==2){
			cout<<w[1]<<endl;
		}
		else if(op==3) pop();
		//for(int i=1;i<=tot;i++) cout<<w[i]<<endl;
	}
	return 0;
}

偶然在深进中看到了手写二叉堆的P3378,试了下,全都RE 不知道为啥 求助

2023/5/20 23:12
加载中...