zoukankan      html  css  js  c++  java
  • C++之priority_queue

    博客转载自:https://www.cnblogs.com/George1994/p/6477198.html

    前言

    之前从没用过优先队列,刷算法题目的时候才开始了解的,所以做个总结。什么情况下使用呢?比如当你需要获取到最大最小值元素,而又不想用最大最小堆的原生实现,STL提供给你更加简单的库,就是priority_queue,其时间复杂度也只有o(nlogn)。

    说明

    根据元素的优先级被读取,这个优先级取决于你设置的排序函数,如果你没设置,缺省的排序法则则是利用operator<形成降序排列,也就是从大到小排列的大顶堆,第一个自然就是最大的元素。还有如果你没设置保存数据的容器Container的话,默认用的是vector。

    namespace std {
        template < class T ,
               class Container = vector<T> ,
               class Compare = less <typename Container::value_type> >
        class priority_queue ;
    }
    

    priority_queue提供了三个基本函数,分别是:

    1. top()
    2. push()
    3. pop()

    注意,pop并不会返回元素,top才会返回堆顶的元素。

    STL提供了仿函数greater<>,less<>,简化了自己再定义排序函数的过程。如果你想使用自己定义的结构,而不想使用基本数据类型,也是ok的,不过你需要在你自定义的类中重载运算符,比如:

    class Student
    {
        int id;
        char name[20];
        bool gender;
        bool operator < (Student &a) const
        {
            return id > a.id;
        }
    };

    使用

    这是一个找输入流的中间值的题目,用最大最小堆实现。

    priority_queue<int, vector<int>, less<int>> maxHeap; //存储小的值,值越大,优先级越高
    priority_queue<int, vector<int>, greater<int>> minHeap; //存储大的值,值越小,优先级越高
    
    /**
     *  完全不需要判断各种判断
     *  不过一定要注意minHeap和maxHeap的优先级顺序,避免弄反了
     */
    void addNum3(int num) {
        minHeap.push(num);
        maxHeap.push(minHeap.top());
        minHeap.pop();
        // 平衡
        if (minHeap.size() < maxHeap.size()) {
            minHeap.push(maxHeap.top());
            maxHeap.pop();
        }
    }
        
    double findMedian3() {
        return maxHeap.size() == minHeap.size() ? (double)(maxHeap.top() + minHeap.top())/2.0 : (double)minHeap.top()/1.0;
    }
        
    void test() {
        this->addNum3(1);
        this->addNum3(2);
        
        cout << this->findMedian3() << endl;
        
        this->addNum2(3);
        
        cout << this->findMedian3() << endl;
    }
    

    输出结果

    1.5
    2

    底层实现

    显然,我们可以看出priority_queue的底层实现是堆实现的。里面的c就是你自己提供的容器Container

    void push(value_type&& _Val)
        {    // insert element at beginning
        c.push_back(_STD move(_Val));
        push_heap(c.begin(), c.end(), comp);
        }
    
    template<class... _Valty>
        void emplace(_Valty&&... _Val)
        {    // insert element at beginning
        c.emplace_back(_STD forward<_Valty>(_Val)...);
        push_heap(c.begin(), c.end(), comp);
        }
    
    
    bool empty() const
        {    // test if queue is empty
        return (c.empty());
        }
    
    size_type size() const
        {    // return length of queue
        return (c.size());
        }
    
    const_reference top() const
        {    // return highest-priority element
        return (c.front());
        }
    
    void push(const value_type& _Val)
        {    // insert value in priority order
        c.push_back(_Val);
        push_heap(c.begin(), c.end(), comp);
        }
    
    void pop()
        {    // erase highest-priority element
        pop_heap(c.begin(), c.end(), comp);
        c.pop_back();
        }
    

     实际使用中将节点存在优先队列中的两种方式

    struct Node
    {
        int x,y;
        bool operator <(Node a) const  {  return y < a.y; }
        bool operator >(Node a) const  {  return y > a.y; }
    };
    priority_queue<Node> A;                    //大根堆
    priority_queue<Node, vector<Node>, greater<Node> > B;    //小根堆 

    方式一

    struct Node
    {int adj;
     int val;
     friend  bool operator<(const Node &a,const Node &b) { return  a.val > b.val; }
    };
    priority_queue<Node>Q; 
    

    方式二:(cmp将结构体以val由大到小排列,组成大根堆)一般也用这个!

    struct Node
    {int adj;
     int val;
    };
    struct cmp
    {bool operator()(Node a,Node b) { return  a.val > b.val; }
    };
    priority_queue<Node,vector<Node>,cmp>Q; 
    

    方式三

    struct TMax
    {
        TMax(int tx):x(tx){}
        int x;
    }; 
    
    struct TMin
    {
        TMin(int tx):x(tx){}
        int x;
    }; 
    
    bool operator<(const TMax &a, const TMax &b)
    {
        return a.x<b.x;
    } 
    
    bool operator<(const TMin &a, const TMin &b)
    {
        return a.x>b.x;
    } 
    
    priority_queue<TMax> hmax;    //大顶堆
    priority_queue<TMin> hmin;    //小顶堆 
    

    3.下面是将指针存在优先队列中的方式

    struct Node
    {
         short f;
         short d;
         short fishs;
         short times;
         short i;
    }; 
    
    struct PCmp
    {
        bool operator () (Node const *x, Node const *y)
        {
            if(x->f == y->f)
                return x->i > y->i;
            return x->f < y->f;
        }
    }; 
    
    priority_queue<Node*, vector<Node*>, PCmp > Q;

    注:在这种情况下往往可以预分配空间以避免new带来的麻烦。例如:堆中定义Node Qt[26], 栈中的使用则为Node *tmp1 = Qt。经过测试,在优选队列当中存指针进行一系列操作要比存节点进行一系列操作快一些。

    注:

    1. less<class T>这是大顶堆,按值大的优先,值大的在最上面。greater<class T>这是小顶堆,按值小的优先,值小的在最上面。
    2. 自定义cmp如果还有不明白的看这里
      struct cmp
      {
       bool operator()(const int &a,const int &b)//这里的&是引用
       {
        return a>b;//最大堆
        return a<b;//最小堆
       }
      };
      priority_queue< int, vector<int>, cmp >
    3. 还是自定义cmp函数,注意,一般ACM中用结构体内含“bool operator()(const int &a,const int &b)”。这其实等价于Class cmp,不过更省事,当然也不规范(不需要规范)。
    4. return就是希望如何排列为true。如果希望由大到小,就将大到小的情况return;反则亦然。和sort的自定义cmp是一样的。
  • 相关阅读:
    Linux Ctrl+Z的使用方法
    cx_Oracle库导入失败引起crontab中python程序运行失败,并且无错误提示
    cx_Oracle库导入失败引起crontab中python程序运行失败,并且无错误提示
    python __file__ 与相对路径
    ORACLE之手动注册监听listener。alter system set local_listener="XXX"
    pl/sql developer 连接本地ORACLE 11g 64位数据库
    在linux设置环境变量
    通过Instant Client包来使用SQL*PLUS
    linux 安装oracle 11g
    plsql developer 使用技巧
  • 原文地址:https://www.cnblogs.com/flyinggod/p/8669272.html
Copyright © 2011-2022 走看看