zoukankan      html  css  js  c++  java
  • 优先对列总结priority_queue

    常规用法:默认从大到小排列。

    #include<iostream>
    #include<queue>
    using namespace std;
    priority_queue<int>que;
    typedef pair<int, int> P;
    int main()
    {
        for (int i = 0; i < 10; i++){
            que.push(i);
        }
    
        while (!que.empty()){
            cout << que.top() << ",";
            que.pop();
        }
        system("pause");
        return 0;
    }

    从小到大排的做法:

    1,

    #include<iostream>
    #include<queue>
    #include<functional>//需要用到greater
    using namespace std;
    priority_queue<int, vector<int>, greater<int>> que;
    typedef pair<int, int> P;
    int main()
    {
        for (int i = 0; i < 10; i++){
            que.push(i);
        }
    
        while (!que.empty()){
            cout << que.top() << "," << endl;
            que.pop();
        }
        system("pause");
        return 0;
    }

    2,

    #include<iostream>
    #include<queue>
    using namespace std;
    struct cmp{
        bool operator()(int x, int y){
            return x > y;    //x越小优先级越高
        }
    };
    priority_queue<int, vector<int>, cmp>que;//这个声明要特别注意两点:vector<int>和cmp
    typedef pair<int, int> P;
    int main()
    {
        for (int i = 0; i < 10; i++){
            que.push(i);
        }
    
        while (!que.empty()){
            cout << que.top() << ",";
            que.pop();
        }
        system("pause");
        return 0;
    }

    若采用自定义结构,自定义优先排序,做法如下:

    #include<iostream>
    #include<queue>
    using namespace std;
    struct node{
        int x, y;
        friend bool operator<(node a, node b){//标准库默认使用 < 来确认它们的关系,换成>就不行了哦
            return a.y>b.y;//>表示越小越优先,<表示越大越优先
        }                    //可以这样记:最大堆与小于号有关,最小堆与大于号有关。这样记会不会好一点呢。。。
    };
    priority_queue<node> que;
    typedef pair<int, int> P;
    int main()
    {
        node v;
        for (int i = 0; i < 10; i++){
            v.x = i;
            v.y = 10 - i;
            que.push(v);
        }
    
        while (!que.empty()){
            cout << que.top().x << "," << que.top().y << endl;
            que.pop();
        }
        system("pause");
        return 0;
    }
    世上无难事,只要肯登攀。
  • 相关阅读:
    城市的划入划出效果
    文本溢出省略解决笔记css
    长串英文数字强制折行解决办法css
    Poj 2352 Star
    树状数组(Binary Indexed Trees,二分索引树)
    二叉树的层次遍历
    Uva 107 The Cat in the Hat
    Uva 10336 Rank the Languages
    Uva 536 Tree Recovery
    Uva10701 Pre, in and post
  • 原文地址:https://www.cnblogs.com/littlehoom/p/3550469.html
Copyright © 2011-2022 走看看