码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2019-10-17 17:45:11      阅读:70      评论:0      收藏:0      [点我收藏+]

标签:ons   oid   stream   int   operator   pre   min   turn   adjust   

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

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;
    }

    int len;
    TYPE num[30005];

    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; //小顶堆
}

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

标签:ons   oid   stream   int   operator   pre   min   turn   adjust   

原文地址:https://www.cnblogs.com/henserlinda/p/11693199.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!