stl自定义排序方式

priority_queue
看病要排队.
方法1(比较好理解)

stl中的vector接受结构体中的运算符重载(非友元)
而set, map, priority_queue不支持(更新:加上const可以)

注意大根堆的排序方式

#include<bits/stdc++.h>
using namespace std;
struct node{
	int index;
	int rank;
	node(int i1,int r1):index(i1),rank(r1){};
	friend bool operator < (node q,node p){//注意大根堆的排序方式,要将排名靠前的人放在后面,所以第一个参数是q,而不是p
		if(p.rank!=q.rank)
			return p.rank>q.rank;
		return p.index<q.index;	
	}
};
priority_queue<node> q[4];
void init(){
	for(int i=1;i<=3;i++){
		while(q[i].size())	q[i].pop();
	}
}
int main(){
	int n;
	while(cin>>n){
		init();
		int pos=0;
		for(int i=1;i<=n;i++){
			string s;
			cin>>s;
			if(s=="IN"){
				int doc,rank;
				cin>>doc>>rank;
				q[doc].push(node(++pos,rank));
			}
			else {
				int doc;
				cin>>doc;
				if(q[doc].empty()){
					cout<<"EMPTY"<<endl;
				}
				else {
					cout<<q[doc].top().index<<endl;
					q[doc].pop();
				}
			}
		}
	}
	return 0;
}

也可以把运算符重载放在结构体外面

#include<bits/stdc++.h>
using namespace std;
struct node {
	int index;
	int rank;
	node(int i1, int r1) :index(i1), rank(r1) {};
};
bool operator < (const node& q, const node& p) {//注意大根堆的排序方式,要将排名靠前的人放在后面,所以第一个参数是q,而不是p
	if (p.rank != q.rank)
		return p.rank > q.rank;
	return p.index < q.index;
}
priority_queue<node> q[4];
void init() {
	for (int i = 1; i <= 3; i++) {
		while (q[i].size())	q[i].pop();
	}
}
int main() {
	int n;
	while (cin >> n) {
		init();
		int pos = 0;
		for (int i = 1; i <= n; i++) {
			string s;
			cin >> s;
			if (s == "IN") {
				int doc, rank;
				cin >> doc >> rank;
				q[doc].push(node(++pos, rank));
			}
			else {
				int doc;
				cin >> doc;
				if (q[doc].empty()) {
					cout << "EMPTY" << endl;
				}
				else {
					cout << q[doc].top().index << endl;
					q[doc].pop();
				}
			}
		}
	}
	return 0;
}

更新,普通的重载似乎也可以, 加个const就行

#include<bits/stdc++.h>
using namespace std;
struct node{
	int index;
	int rank;
	node(int i1,int r1):index(i1),rank(r1){};
	bool operator < (const node& p) const {//注意大根堆的排序方式,要将排名靠前的人放在后面,所以第一个参数是q,而不是p
		if(rank!=q.rank)
			return rank>q.rank;
		return index<q.index;	
	}
};
priority_queue<node> q[4];
void init(){
	for(int i=1;i<=3;i++){
		while(q[i].size())	q[i].pop();
	}
}
int main(){
	int n;
	while(cin>>n){
		init();
		int pos=0;
		for(int i=1;i<=n;i++){
			string s;
			cin>>s;
			if(s=="IN"){
				int doc,rank;
				cin>>doc>>rank;
				q[doc].push(node(++pos,rank));
			}
			else {
				int doc;
				cin>>doc;
				if(q[doc].empty()){
					cout<<"EMPTY"<<endl;
				}
				else {
					cout<<q[doc].top().index<<endl;
					q[doc].pop();
				}
			}
		}
	}
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值