c++ - 优先级队列和堆之间的区别

标签 c++ algorithm heap priority-queue

似乎优先级队列只是一个具有正常队列操作(如插入、删除、顶部等)的堆。这是解释优先级队列的正确方法吗?我知道您可以以不同的方式构建优先级队列,但是如果我要从堆构建优先级队列,是否有必要创建一个优先级队列类并提供构建堆和队列操作的说明,或者真的不需要构建上课?

我的意思是,如果我有一个构建堆的函数和执行插入和删除等操作的函数,我是否需要将所有这些函数放在一个类中,或者我可以通过在 main 中调用它们来使用指令。

我想我的问题是拥有一组函数是否等同于将它们存储在某个类中并通过一个类使用它们,或者只是使用函数本身。

下面是优先级队列实现的所有方法。这足以将其称为实现还是我需要将其放入指定的优先级队列类中?

#ifndef MAX_PRIORITYQ_H
#define MAX_PRIORITYQ_H
#include <iostream>
#include <deque>
#include "print.h"
#include "random.h"

int parent(int i)
{
    return (i - 1) / 2;
}

int left(int i)
{
    if(i == 0)
        return 1;
    else
        return 2*i;
}

int right(int i)
{
    if(i == 0)
        return 2;
    else
        return 2*i + 1;
}

void max_heapify(std::deque<int> &A, int i, int heapsize)
{
    int largest;
    int l = left(i);
    int r = right(i);
    if(l <= heapsize && A[l] > A[i])
        largest = l;
    else
        largest = i;
    if(r <= heapsize && A[r] > A[largest])
        largest = r;
    if(largest != i) {
        exchange(A, i, largest);
        max_heapify(A, largest, heapsize);
        //int j = max_heapify(A, largest, heapsize);
        //return j;
    }
    //return i;
}

void build_max_heap(std::deque<int> &A)
{
    int heapsize = A.size() - 1;
    for(int i = (A.size() - 1) / 2; i >= 0; i--)
        max_heapify(A, i, heapsize);
}

int heap_maximum(std::deque<int> &A)
{
    return A[0];
}

int heap_extract_max(std::deque<int> &A, int heapsize)
{
    if(heapsize < 0)
        throw std::out_of_range("heap underflow");
    int max = A.front();
    //std::cout << "heapsize : " << heapsize << std::endl;
    A[0] = A[--heapsize];
    A.pop_back();
    max_heapify(A, 0, heapsize);
    //int i = max_heapify(A, 0, heapsize);
    //A.erase(A.begin() + i);
    return max;
}

void heap_increase_key(std::deque<int> &A, int i, int key)
{
    if(key < A[i])
        std::cerr << "New key is smaller than current key" << std::endl;
    else {
        A[i] = key;
        while(i > 1 && A[parent(i)] < A[i]) {
            exchange(A, i, parent(i));
            i = parent(i);
        }
    }
}

void max_heap_insert(std::deque<int> &A, int key)
{
    int heapsize =  A.size();
    A[heapsize] = std::numeric_limits<int>::min();
    heap_increase_key(A, heapsize, key);
}

最佳答案

优先级队列是 abstract datatype .它是描述特定接口(interface)和行为的简写方式,不涉及底层实现。

堆是 data structure .它是一种特殊的数据存储方式的名称,可以使某些操作非常高效。

恰好堆是实现优先级队列的一个很好的数据结构,因为堆数据结构高效的操作是优先级队列接口(interface)需要的操作。

关于c++ - 优先级队列和堆之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18993269/

相关文章:

algorithm - 计算递归算法的时间复杂度

Scala 有序优先级队列,始终以最低编号作为头,升序排列

memory - "a"堆和 "the"堆有什么关系?

c++ - 避免在 Qt 中使用非符号常量

c++ - MSVC++ : template's static_assert is not triggered inside a lambda

algorithm - 在 R 中,相当于 upper_bound()

计算字符串中的单词出现次数

JAVA-PriorityQueue实现

c++ - 未定义对 QMediaPlayer 和 QVideoWidget 的引用

Windows 上的 iPhone 应用程序开发