百练 / 2017大数据研究中心夏令营上机考试 G: 双队列

题目来源:http://dsalgo.openjudge.cn/advance/8/

G:双队列

总时间限制1000ms   内存限制65536kB

描述

系统A用来维护客户。每个客户的id用一个正整数K来表示,当客户进入系统时用P来表示此用户的优先度。这个系统有以下请求

0

系统停止运行

K P

优先度为P的客户K进入系统

2

找到优先度最高的客户,然后此客户离开系统

3

找到优先度最低的客户,然后此客户离开系统

输入

每行包括一个请求,最后一行包括一个停止请求(代码0)。对于添加客户请求(代码1),优先度都是唯一的。客户的表示K小于106,优先度P小于107,一个客户可能会被添加多次,每次的优先度可能不同。

输出

对于每个请求23,程序必须输出一行。这行包括此请求中找到客户的id。如果系统中没有客户,输出0

样例输入

2
1 20 14
1 30 3
2
1 10 99
3
2
2
0

样例输出

0
20
30
10
0

------------------------------------------------------------

思路

维护一个优先级p最高的优先队列和一个优先级p最低的优先队列。读入指令2和3时分别对两个队列的对首进行操作。由于一个优先队列里对首出队时另一个队列里的相应元素不容易找到,因此设置一个计数器保存此时系统中存储客户的个数,如果cnt==0在指令2和3时就输出0

注意priority_queue第三项比较项只能用类(结构体),不能用函数,结构体中重载"()"运算符来做比较。具体可以参见这篇博文:priority_queue

------------------------------------------------------------

代码

#include<iostream>
#include<fstream>
#include<queue>
#include<vector>
using namespace std;

struct node {
	int id, p;

	node (void) {}
	node (int ii, int pp): id(ii), p(pp){}
};

struct myless {
	bool operator () (const node &a, const node &b)
	{
		return a.p > b.p;
	}
};

struct mygreater {
	bool operator () (const node &a, const node &b)
	{
		return a.p < b.p;
	}
};

int main()
{
#ifndef ONLINE_JUDGE
	ifstream fin ("G.txt");
	priority_queue<node,vector<node>,myless> up;
	priority_queue<node,vector<node>,mygreater> down;
	int in, id, p, cnt = 0;
	while (fin >> in)
	{
		if (in==0)
		{
			break;
		}
		else if (in==1)
		{
			fin >> id >> p;
			up.push(node(id,p));
			down.push(node(id,p));
			cnt++;
		}
		else if (in==2)
		{
			if (cnt==0)
			{
				cout << 0 << endl;
			}
			else
			{
				cout << down.top().id << endl;
				down.pop();
				cnt--;
			}
		}
		else if (in==3)
		{
			if (cnt==0)
			{
				cout << 0 << endl;
			}
			else
			{
				cout << up.top().id << endl;
				up.pop();
				cnt--;
			}
		}
	}
	fin.close();
#endif
#ifdef ONLINE_JUDGE
	priority_queue<node,vector<node>,myless> up;
	priority_queue<node,vector<node>,mygreater> down;
	int in, id, p, cnt = 0;
	while (cin >> in)
	{
		if (in==0)
		{
			break;
		}
		else if (in==1)
		{
			cin >> id >> p;
			up.push(node(id,p));
			down.push(node(id,p));
			cnt++;
		}
		else if (in==2)
		{
			if (cnt==0)
			{
				cout << 0 << endl;
			}
			else
			{
				cout << down.top().id << endl;
				down.pop();
				cnt--;
			}
		}
		else if (in==3)
		{
			if (cnt==0)
			{
				cout << 0 << endl;
			}
			else
			{
				cout << up.top().id << endl;
				up.pop();
				cnt--;
			}
		}
	}
#endif
}


猜你喜欢

转载自blog.csdn.net/da_kao_la/article/details/81045530
今日推荐