zoukankan      html  css  js  c++  java
  • 转 优先队列 的使用

    优先队列使用

    这个是转得网上的,由于不经常使用,偶尔用的时候还经常出错,所以记下来了,经常使用的已经用红色颜色标出来了 :

    在优先队列中,优先级高的元素先出队列。
    标准库默认使用元素类型的<操作符来确定它们之间的优先级关系。
    优先队列的第一种用法,也是最常用的用法:

    priority_queue<int> qi;

    通过<操作符可知在整数中元素大的优先级高。
    故示例1中输出结果为:9 6 5 3 2

    第二种方法:
    在示例1中,如果我们要把元素从小到大输出怎么办呢?
    这时我们可以传入一个比较函数,使用functional.h函数对象作为比较函数。

    priority_queue<int, vector<int>, greater<int> >qi2;

    其中
    第二个参数为容器类型。
    第二个参数为比较函数。
    故示例2中输出结果为:2 3 5 6 9

    第三种方法:
    自定义优先级。

    struct node
    {
        friend bool operator< (node n1, node n2)
        {
            return n1.priority < n2.priority;
        }
        int priority;
        int value;
    };

    在该结构中,value为值,priority为优先级。
    通过自定义operator<操作符来比较元素中的优先级。
    在示例3中输出结果为:
    优先级  值
    9          5
    8          2
    6          1
    2          3
    1          4
    但如果结构定义如下:

    struct node
    {
        
    friend bool operator> (node n1, node n2)
        {
            
    return n1.priority > n2.priority;
        }
        
    int priority;
        
    int value;
    };

    则会编译不过(G++编译器)
    因为标准库默认使用元素类型的<操作符来确定它们之间的优先级关系。
    而且自定义类型的<操作符与>操作符并无直接联系,故会编译不过。

    补充的一点是:

    我们可以自己写一个比较类,还设定优先级:

    struct cmp
    {
        bool operator() (const int &a, const int &b)
        {
            return dist[a] > dist[b];
        }
    };

    priority_queue<int,vector<int>,cmp> q;(按照元素的dist大小从小到大排序).

  • 相关阅读:
    I NEED A OFFER!
    水题 Codeforces Round #303 (Div. 2) A. Toy Cars
    模拟 HDOJ 5099 Comparison of Android versions
    模拟 HDOJ 5095 Linearization of the kernel functions in SVM
    贪心 HDOJ 5090 Game with Pearls
    Kruskal HDOJ 1863 畅通工程
    Kruskal HDOJ 1233 还是畅通工程
    并查集 HDOJ 1232 畅通工程
    DFS/并查集 Codeforces Round #286 (Div. 2) B
    水题 Codeforces Round #286 (Div. 2) A Mr. Kitayuta's Gift
  • 原文地址:https://www.cnblogs.com/assult/p/3131292.html
Copyright © 2011-2022 走看看