优先队列

元素入队时间复杂度O(logn),查询O(1),总体排序时间复杂度O(logn),用于优化一些大数据范围的排序,具体用法如下:
#include<bits/stdc++.h>
using namespace std;

priority_queue <int,vector<int>,less<int> > q; //less<int>:和greater<int>相反 

struct node{
    int i,v;
};
priority_queue <node> q1;

bool operator < (const node &x, const node &y){ //重载"<",排序规则与实际规则相反 
    if(x.v == y.v) return x.i > y.i;
    return x.v > y.v;
}
int main(){
    int n,t;
    cin >> n;
    for(int i = 1;i <= n;i++){
        cin >> t;
        q.push(t); 
        q1.push((node){i,t});
    }
    while(q1.size()){
        cout << q.top() << endl;
        q.pop();
        cout << q1.top().i << " " << q1.top().v << endl;
        q1.pop();
    }
    return 0;
}

 

posted @ 2023-08-04 17:22  待到春来蕴  阅读(23)  评论(0)    收藏  举报