• 大顶堆的基本操作(线性表建堆+siftup+siftdown+insert+delete)


    #include<bits/stdc++.h>
    using namespace std;
    typedef unsigned int ui;
    typedef long long ll;
    typedef unsigned long long ull;
    #define pf printf
    #define mem(a,b) memset(a,b,sizeof(a))
    #define prime1 1e9+7
    #define prime2 1e9+9
    #define pi 3.14159265
    #define lson l,mid,rt<<1
    #define rson mid+1,r,rt<<1|1
    #define scand(x) scanf("%llf",&x) 
    #define f(i,a,b) for(int i=a;i<=b;i++)
    #define scan(a) scanf("%d",&a)
    #define dbg(args) cout<<#args<<":"<<args<<endl;
    #define pb(i) push_back(i)
    #define ppb(x) pop_back(x)
    #define inf 0x3f3f3f3f
    #define maxn 100005
    int n=100,m,t;
    
    void siftup(int* h,int x)
    {
        if(x==1)return;//根节点 
        int p=x/2;
        while(h[p]<h[x]&&p>=1)
        {
            swap(h[p],h[x]);
            p=x/2;
        } 
    }
    void siftdown(int* h,int x)
    {
        bool done=false;
        while(2*x<=n&&!done)
        {
            int tmp=x;
            x*=2;
            if(x+1<=n&&h[x+1]>h[x])x++;
            if(h[x]>h[tmp])swap(h[x],h[tmp]);
            else {
                done=true;
            }
        }
    }
    void insert(int* h,int a)
    {
        n++;
        h[n]=a;
        siftup(h,n);
    }
    void del(int* h,int a)
    {
        if(a==n)return;
        int y=h[n],x=h[a];
        h[a]=y;
        n--;
        if(x>y)siftdown(h,a);
        else siftup(h,a); 
    }
    int delmax(int *h)
    {
        int x=h[1];
        del(h,1);
        return x;
    }
    void build(int* a,int len)
    {
        int l=len/2;
        for(int i=l;i>0;i--)
        {
            siftdown(a,i);
        }
    }
    void print(int* h)
    {
        f(i,1,100)pf("%d ",h[i]);
        pf("
    ");
    }
    int h[maxn];
    
    int main()
    {
        //freopen("input.txt","r",stdin);
        //freopen("output.txt","w",stdout);
        std::ios::sync_with_stdio(false);
        for(int i=100;i>=1;i--)
        {
            h[i]=i;
        }
        print(h);
        build(h,n);
        f(i,1,100)
        {
            pf("%d ",delmax(h));
        }
     } 
  • 相关阅读:
    hashlib模块
    configparser模块
    xml模块和shelve模块
    json与pickle模块
    3/30
    os模块
    sys模块
    shutil模块
    random模块
    2月书单《编码隐匿在计算机软硬件背后的语言》 13-16章
  • 原文地址:https://www.cnblogs.com/randy-lo/p/13131240.html
Copyright © 2020-2023  润新知