zoukankan      html  css  js  c++  java
  • 堆的基本操作

    一直都想了解堆

    学习来自这篇

    http://www.cnblogs.com/JVxie/p/4859889.html

    #include<stdio.h>
    #include<string.h>
    #include<algorithm>
    
    using namespace std;
    #define MAXN 100010
    struct Heap  //小顶堆
    {
        int Size;
        int z[MAXN];
    
        void push(int a)
        {
            z[++Size]=a;
            shift_up(Size);
        }
        void shift_up(int a) //上浮
        {
            while(a>1)
            {
                if(z[a>>1]>z[a])
                    swap(z[a>>1],z[a]);
                a=a>>1;
            }
        }
        void shift_down(int a)
        {
            while((a<<1)<=Size)
            {
                int b=a<<1;
                if(b<Size&&z[b]>z[b+1])
                    b++;
                if(z[a]>z[b])
                {
                    swap(z[a],z[b]);
                    a=b;
                }
                else
                    return ;
            }
        }
        void pop()           //弹出栈顶
        {
            swap(z[1],z[Size]);
            Size--;
            shift_down(1);
        }
        bool empty()
        {
            return Size?0:1;
        }
        int top()
        {
            return z[1];
        }
    };
    
    int main()
    {
        Heap Q;
        memset(Q.z,0,sizeof(Q.z));
        Q.Size=0;
        int n;
        scanf("%d",&n);
    /*
    5
    2 3 4 1 6
    
    */
        for(int i=1;i<=n;i++)
        {
            int a;
            scanf("%d",&a);
            Q.push(a);
        }
        for(int i=1;i<=6;i++)
        {
            if(!Q.empty())  //每个都弹出堆就是堆排序
            {
                int a=Q.top();
                printf("%d ",a);
                Q.pop();
            }
            else
                printf("no
    ");
        }
        printf("
    ");
        return 0;
    }
  • 相关阅读:
    第09组 Beta冲刺(2/5)
    第09组 Beta冲刺(3/5)
    第09组 Beta冲刺(4/5)
    第09组 Beta冲刺(5/5)
    第09组 Beta冲刺(1/5)
    SDN课程阅读作业(2)
    C语言I作业07
    C语言I博客作业05
    C语言I博客作业04
    C语言I博客作业03
  • 原文地址:https://www.cnblogs.com/cherryMJY/p/6142488.html
Copyright © 2011-2022 走看看