admin管理员组

文章数量:1623803

优先队列--自定义排序

    • A: 默认排序
    • B: 自定义排序
      •        方法一: 运算符重载
      •        方法二: 重写仿函数

A: 默认排序

1,priority_queue< int > a;     // 基础类型, 默认是大顶堆,自动排

2,priority_queue<int, vector< int >, greater< int > > c;     //基础类型,变小根堆

#include<bits/stdc++.h>
#define ll long long
#define PP pair<int,int>
using namespace std;

int main()
{
    priority_queue< int,vector<int>,greater<int> > q;
    q.push(1);
    q.push(5);
    q.push(3);

    while(!q.empty())
    {
        printf("%d\n",q.top());
        q.pop();
    }

    return 0;
}

B: 自定义排序

       方法一: 运算符重载

结构体内 重载运算符<

#include<bits/stdc++.h>
#define ll long long
using namespace std;

#define PP pair<int,int>

struct Node{

    int x,y,z;
    Node(int a,int b,int c)
    {
        x=a,y=b,z=c;
    }
    bool operator<(const Node &a) const   //*****  运算符重载 < ,内置
    {
        return a.z>z;  //按z值降序
    }
};

int main()
{
    priority_queue<Node> q;
    q.push(Node(1,2,3));
    q.push(Node(3,9,1));
    q.push(Node(2,3,4));
    while(!q.empty())
    {
        printf("%d %d %d\n",q.top().x,q.top().y,q.top().z);
        q.pop();
    }

    return 0;
}

       方法二: 重写仿函数

priority_queue< 类型,vector< 类型 >,cmp> q;

#include<bits/stdc++.h>
#define ll long long
using namespace std;

#define PP pair<int,int>

struct cmp{    
            //重写仿函数
   bool operator()(PP a,PP b)
   {
       return a.first>b.first;
   }

};

int main()
{
     priority_queue<PP,vector<PP>,cmp> q;

     q.push(make_pair(4,6));
     q.push(make_pair(9,4));
     q.push(make_pair(6,1));
     while(!q.empty())
     {
         printf("%d %d\n",q.top().first,q.top().second);
         q.pop();
     }

    return 0;
}

本文标签: 队列自定义priorityqueue