zoukankan      html  css  js  c++  java
  • 手写堆

    #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();
       }
    }
  • 相关阅读:
    编码
    浏览器翻页
    验证码识别
    时间
    phantomjs配置
    产品
    java范型的理解
    使用JDBC连接数据库
    垃圾回收机制
    java的内存区域 && java内存模型
  • 原文地址:https://www.cnblogs.com/acmLLF/p/14727365.html
Copyright © 2011-2022 走看看