zoukankan      html  css  js  c++  java
  • 优先队列:自定义优先级

    priority_queue<Type, container,compare>
    • Type: Type of the elements.
    • Container: Type of the underlying container object used to store and access the elements
    • Compare: Comparison class: A class such that the expression comp(a,b), where comp is an object of this class and a and b are elements of the container, returns true if a is to be placed earlier than b in a strict weak ordering operation. This can either be a class implementing a function call operator or a pointer to a function. This defaults to less<T>, which returns the same as applying the less-than operator (a<b).
      The priority_queue object uses this expression when an element is inserted or removed from it (using push or pop, respectively) to grant that the element popped is always the greatest in the priority queue.
    优先队列默认<操作符,即元素值大的优先级高。
    自定义优先级有2种方法:
         1、自定义compare类
         2、在struct或class中重载运算符
     
    方法1:
    #include<iostream>
    #include<vector>
    #include<queue>
    
    using namespace std;
    
    struct cmp
    {
        bool operator()(int a,int b)
        {
            return a>b;    
        }      
    };
    
    int main()
    {
        priority_queue<int,vector<int>,cmp> q;
        q.push(4);
        q.push(2);
        q.push(9);
        q.push(6);
       
        while(!q.empty())
        {
            cout<<q.top()<<" ";
            q.pop();               
        }
        cout<<endl;   
        system("pause");
        return 0;   
    }

    方法2:

    #include<iostream>
    #include<vector>
    #include<queue>
    
    using namespace std;
    
    struct node
    {
        int v;
        bool operator<(node t) const
        {
            return v>t.v;     
        }       
    }a[5];
    
    int main()
    {
        priority_queue<node> q;
        
        for(int i=5;i>=1;i--)
        {
            a[i].v=i;
            q.push(a[i]);        
        }
      
        while(!q.empty())
        {
            cout<<(q.top()).v<<" ";
            q.pop();                
        }
        cout<<endl;    
        system("pause");
        return 0;    
    }
  • 相关阅读:
    Luogu 2254 [NOI2005]瑰丽华尔兹
    Luogu 3168 [CQOI2015]任务查询系统
    Luogu U15118 萨塔尼亚的期末考试(fail)
    POJ 2778 DNA Sequence AC自动机 + 矩阵快速幂
    HDU 2457 DNA repair AC自动机 + dp
    POJ 3522 Slim Span 暴力枚举 + 并查集
    POJ 2955 Brackets 区间dp
    hdu 2604 Queuing dp找规律 然后矩阵快速幂。坑!!
    UESTC
    java & SQL
  • 原文地址:https://www.cnblogs.com/icfnight/p/3239097.html
Copyright © 2011-2022 走看看