UVa 540 STL队列queue的简单应用

题目大致意思是开头给出队列数,每个队列人数,以及队列里的成员编号

然后大家排长队,如果有一对的人就插队到同队的人之后,没有则到整条队伍之后

代码如下:

#include<iostream>
#include<fstream>
#include<map>
#include<queue>
#include<algorithm>
using namespace std;
typedef queue<int> Team;

//题目给出队列范围1<=n<=1000
const int maxn = 1000;
int main()
{
	//freopen("my_ans.txt", "w", stdout);
	int n, rnd = 1;
	while (cin >> n) {
		if (!n) break;
		cout << "Scenario #" << rnd++ << endl;
// 用map记录每个人属于的队伍
		map<int, int> peopleMap;
// team记录队列顺序,people数组记录对应队列里有了哪些人
		Team team, people[maxn + 1];

		for (int i = 0; i < n; i++)
		{
			int j; cin >> j;
			for (int k = 0; k < j; k++) { int id; cin >> id; peopleMap.insert({ id,i }); }
		}

		string cmd;
		while (cin >> cmd)
		{
			if (cmd == "STOP") { cout << endl; break; }
			else if (cmd == "ENQUEUE")
			{
				int id; cin >> id; int whichTeam = peopleMap[id];
// 如果所属队伍里还没人则到长队尾
				if (people[whichTeam].empty()) { team.push(whichTeam); people[whichTeam].push(id); }
// 否则插队到自己队伍
				else people[whichTeam].push(id);
			}
// 偷懒了,这里的else指 DEQUEUE 命令
			else {
// 目前排在长队首的队伍
				int whichTeam = team.front();
				cout << people[whichTeam].front() << endl; people[whichTeam].pop();
// 如果长队首的队伍人走光了从长队中中pop
				if (people[whichTeam].empty()) team.pop();
			}
		}
	}
	return 0;
}

我完成给定数据范围的题目常犹豫,因为感觉空间复杂度高,但数组完成真的很方便快捷

总结:queue 队列没有迭代器,不支持随机访问(所以people[ ] 这里用数组才是可行选择)

这个题有点分治的感觉,队列排队列的,人排人的

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值