手写堆

#include<iostream>
#include<bits/stdc++.h>
using namespace std;


class hip
{

    public:
    int *a;
    int cnt;
    hip(){a=0,cnt=0;}
    hip(int arr[],int n)
    {
       cnt=n;
       a=new int[n];
       for(int i=0;i<n;i++)
        a[i]=arr[i];
       for(int i=n-1;i>=0;i--)
       {  
        down(i);
       }
    }
    int top()
    {
      return a[0];
    }
    int getsize()
    {
        return cnt;
    }
    void down(int cur)
    {
          while(cur<cnt)
          {
                int next=-1;
                int l=cur*2+1,r=cur*2+2;
                int _max=INT_MAX;
                if(l<cnt&&a[l]<_max)
                {
                      next=l;
                      _max=a[l];
                }
                swap(l,r);
                if(l<cnt&&a[l]<_max)
                {
                      next=l;
                      _max=a[l];
                }
                if(next==-1)
                  break;
                if(_max>=a[cur])
                  break;
                swap(a[cur],a[next]);
                cur=next;
          }
    }
    
    void pop()
    {
       swap(a[0],a[cnt-1]);
       cnt--;
       down(0);
    }
};
const int maxn=1e5;
int a[maxn];
int main()
{
   int n;
   cin>>n;
   for(int i=0;i<n;i++)
    cin>>a[i];
   hip que=hip(a,n);
   while(que.getsize())
   {
     cout<<que.top()<<' ';
     que.pop();
   }
}
原文地址:https://www.cnblogs.com/acmLLF/p/14727365.html