手写堆(邦的轩辕)

#include<bits/stdc++.h>
using namespace std;
   int heap[100000];
   int n=0;
void  up(int p)//建立小根堆,p为建立的顺序 
{
	while(p>1)
	{
		if(heap[p]<heap[p/2])
		{
			swap(heap[p],heap[p/2]);
			p=p/2;
			
		}
		else break; 
	}
}

   void insert(int val){
  	heap[++n]=val;//进行点的输入 
    up(n);	
    }
    int gettop()
	{
		
		return heap[1];//取堆顶 ,因为是小根堆,所以取出来的是最小值; 
	 } 
void down(int p){
	int s=p*2;
	while(s<=n){
    if(s<n&&heap[s]>heap[s+1])//删除较大的值
    s++;
    if(heap[s]<heap[p])//s为儿子节点,p为父节点; 
     {
	swap(heap[s],heap[p]);//继续倍增,向下延伸; 
  p=s,s=p*2;
     }
	else break;//防止死循环; 
	} 
	
} 
void extract(){
	heap[1]=heap[n--];
	down(1);	
}
    int main()
  {
	  int m;
	  int zhi[1000000],string[1000000];
	  cin>>m;
	   for(int i=1;i<=m;i++)
	   {
	   cin>>string[i];
	   if(string[i]==1)
	   cin>>zhi[i],insert(zhi[i]);
       if(string[i]==2)
       cout<<gettop()<<endl;
       if(string[i]==3)
       extract();
	   }
	   return 0;
}

手写堆注释在代码里

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值