STL中优先队列(堆)和自定义最大堆最小堆

STL中优先队列(堆)和自定义最大堆最小堆

    • 引言
    • 最大堆的一个例子
    • 最小堆的一个例子

引言

在算法实践中,有的算法要求不停地插入或移除最大或最小值。若用线性比较,则时间复杂度为O( n 2 n^2 n2)。这时候,若用优先队列,则可有效降低时间复杂度。优先队列又称为堆。它的复杂度为O(logN). 当N比较大时,能够有效降低计算时间。优先队列可以用数组自己实现。若对自己的实现没有把握,则可用STL自带的模板。不过需要通过定义操作符,从而定义最大堆和最小堆。
#include

最大堆的一个例子

// An highlighted block
struct Node {
    int value;
    int idx;
    Node (int v, int i): value(v), idx(i) {}
    friend bool operator < (const struct Node &n1, const struct Node &n2) ; 
};
inline bool operator < (const struct Node &n1, const struct Node &n2) {
    return n1.value < n2.value;
}

priority_queue<Node> pq; // 此时pq为最大堆
————————————————
例子链接:https://blog.csdn.net/nisxiya/article/details/45725857

最小堆的一个例子

struct Node {
int value;
int idx;
Node (int v, int i): value(v), idx(i) {}
friend bool operator > (const struct Node &n1, const struct Node &n2) ;
};

inline bool operator > (const struct Node &n1, const struct Node &n2) {
return n1.value > n2.value;
}
priority_queue pq; // 此时greater会调用 > 方法来确认Node的顺序,此时pq是最小堆
————————————————
例子链接:https://blog.csdn.net/nisxiya/article/details/45725857

你可能感兴趣的:(数据结构)