自己封装的优先队列,堆实现

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#define MAX_H nodes1
#define MIN_H nodes2
#define LL int

using namespace std;

struct nodes1
{
    LL k;
    bool operator <(const nodes1 &b) const
    {
        return k < b.k;
    }
};

struct nodes2
{
    LL k;
    bool operator <(const nodes2 &b) const
    {
        return k > b.k;
    }
};


template <class TYPE>
class Que
{
public:
    Que()
    {
        len = 0;
        num = new TYPE[1000005];
    }

    ~Que()
    {
        delete num;
        num = NULL;
    }

    int len;
    TYPE *num;

    void adjust_d(TYPE num[], int cur, int n)
    {
        int i = cur,j = i*2+1;
        //printf("ij: %d %d\n", i, j);
        //printf("%d\n",n);
        while(j < n)
        {
            if(j+1 < n)
                j = num[j]<num[j+1]?j+1:j;

            if(num[i]<num[j])
            {
                swap(num[i],num[j]);
                //printf("swap: %d %d\n", i, j);
                i = j;
                j = i*2+1;
            }
            else
                break;
        }
    }

    void adjust_a(TYPE num[], int cur)
    {
        int i = cur,j = (i-1)/2;
        //printf("ij: %d %d\n", i, j);
        //printf("%d\n",n);
        while(j >= 0)
        {
            if(num[j]<num[i])
            {
                swap(num[i],num[j]);
                //printf("swap: %d %d\n", i, j);
                i = j;
                j = (i-1)/2;
            }
            else
                break;
        }
    }

    void push(TYPE tmp)
    {
        num[len++] = tmp;
        adjust_a(num,len-1);
    }

    TYPE top()
    {
        return num[0];
    }

    void pop()
    {
        swap(num[0],num[len-1]);
        len--;
        adjust_d(num,0,len);
    }

    bool empty()
    {
        if(len == 0)
            return true;
        return false;
    }

    int size()
    {
        return len;
    }
};



void solve()
{
    int n,m;
    Que<MAX_H> Q_max; //大顶堆
    Que<MIN_H> Q_min; //小顶堆
}

posted on 2019-10-17 17:01  鱼泪儿  阅读(93)  评论(0编辑  收藏  举报

导航