题目大致意思是开头给出队列数,每个队列人数,以及队列里的成员编号
然后大家排长队,如果有一对的人就插队到同队的人之后,没有则到整条队伍之后
代码如下:
#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[ ] 这里用数组才是可行选择)
这个题有点分治的感觉,队列排队列的,人排人的