手搓数组堆求调,悬关
查看原帖
手搓数组堆求调,悬关
1163927
F1NE楼主2024/3/21 20:37
#include<bits/stdc++.h>
using namespace std;
int heap[1000009],endd=0,n;
inline void swap(int &a,int &b){a^=b,b=a^b,a^=b;}
inline int min(int a,int b){return a<b?a:b;}
inline void push(int x){
	endd++;
	int tmp=endd;
	heap[tmp]=x;
	while(x<heap[tmp/2]){
		swap(heap[tmp],heap[tmp/2]);
		tmp/=2;
	}
	return;
}
inline void pop(){
	swap(heap[1],heap[endd]);
	heap[endd]=0;endd--; 
	int tmp=1;
	while(tmp*2+1<=endd&&(heap[tmp]>heap[tmp*2]||heap[tmp]>heap[tmp*2+1])){
		if(heap[tmp]>heap[tmp*2]){
			swap(heap[tmp],heap[tmp*2]);//tmp*=2;printf("endd=%d,heap[tmp]=%d,heap[tmp*2]=%d\n",endd,heap[tmp],heap[tmp*2]);
		}else{
			swap(heap[tmp],heap[tmp*2+1]);tmp=tmp*2+1;//printf("endd=%d,heap[tmp]=%d,heap[tmp*2+1]=%d\n",endd,heap[tmp],heap[tmp*2+1]);
		}
	}
	return; 
}
int main(){
	cin>>n;
	for(int i=1,op,x;i<=n;i++){
		scanf("%d",&op);
		if(op==1){
			scanf("%d",&x);push(x);
		}
		if(op==2){
			printf("%d\n",heap[1]);
		}
		if(op==3) pop();
		//for(int j=1;j<=endd;j++) cout<<heap[j]<<' ';cout<<"heap"<<endl;
	}
	return 0;
} 
2024/3/21 20:37
加载中...