zoukankan      html  css  js  c++  java
  • c++中小项堆声明和使用

    c++默认是大顶堆,小顶堆有两种声明方法:

    1、对于基本类型直接用

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

    如果基本类型是pair:

    在代码第一行写:

    typedef pair<int, int> P;

     priority_queue<P, vector<P>, greater<P>>pq;

    注:greater<int> 是个好东西,把一个vector v从大到小排序用的就是sort(v.begin(), v.end(), greater<int>());

    2、对于自定义类型,则必须自己重载 operator< 或者自己写仿函数

    #include <iostream>

    #include <queue>

    using namespace std;

    struct Node{
        int x, y;
        Node( int a= 0, int b= 0 ):
            x(a), y(b) {}
    };

    struct cmp{
        bool operator() ( Node a, Node b ){
            if( a.x== b.x ) return a.y> b.y;
           
            return a.x> b.x; }
    };

    int main(){
        priority_queue<Node, vector<Node>, cmp> q;
       
        for( int i= 0; i< 10; ++i )
        q.push( Node( rand(), rand() ) );
       
        while( !q.empty() ){
            cout << q.top().x << ' ' << q.top().y << endl;
            q.pop();
        }
       
        getchar();
        return 0;
    }

  • 相关阅读:
    并查集
    关于一些位运算的小记
    用ST解决RMQ问题
    寒假作业_4
    H
    卢卡斯 组合数
    并查集
    G
    F
    E
  • 原文地址:https://www.cnblogs.com/yanchengwang/p/6184514.html
Copyright © 2011-2022 走看看