题目描述
组队列是队列结构中一种常见的队列结构,在很多地方有着广泛应用。组队列是是指队列内的元素分组聚集在一起。组队列包含两种命令:
1、 ENQUEUE,表示当有新的元素进入队列,首先会检索是否有同一组的元素已经存在,如果有,则新元素排在同组的最后,如果没有则插入队列末尾。
2、 DEQUEUE,表示队列头元素出队
3、 STOP,停止操作
建议使用C++自带的队列对象queue,编程更方便
输入
第1行输入一个t(t<=10),表示1个队列中有多少个组
第2行输入一个第1组的元素个数和数值
第3行输入一个第2组的元素个数和数值
以此类推输入完t组以定义同组元素之后,开始输入多个操作命令(<200),对空的组队列进行操作,例如输入ENQUEUE 100,表示把元素100插入队列
输出
DEQUEUE出队的元素
输入样例
2
3 101 102 103
3 201 202 203
ENQUEUE 101
ENQUEUE 201
ENQUEUE 102
ENQUEUE 202
ENQUEUE 103
ENQUEUE 203
DEQUEUE
DEQUEUE
DEQUEUE
STOP
输出样例
101 102 103
提示
3 101 102 103
3 201 202 203
3 301 302 303
ENQUEUE 201 ==>>> | 201 |
ENQUEUE 301 ==>>> | 201 | 301 |
ENQUEUE 102 ==>>> | 201 | 301 | 102 |
ENQUEUE 101 ==>>> | 201 | 301 | 102 101 |
ENQUEUE 203 ==>>> | 201 203 | 301 | 102 101 |
ENQUEUE 302 ==>>> | 201 203 | 301 302 | 102 101 |
可以看到队列分组,先入队的组在队列中靠前,出队也靠前:
DEQUEUE
输出 201,队列变为| 203 | 301 302 | 102 101 |
…
#include<iostream>
#include<stack>
#include<queue>
#include<string>
#include<cstring>
#include<string.h>
#include<map>
using namespace std;
queue<int> Myqe[12]; 用于保存每个子队列的数据
queue<int> lev; ///记录子队列的输出顺序
int main()
{
int t;
cin >> t;
int a[10][10];
int len = 4;
for (int i = 1; i <= t; i++)
{
int xlen;
cin >> xlen;
if (len < xlen)
{
len = xlen;
}
for (int j = 1; j <= xlen; j++)
{
cin >> a[i][j];
}
}
string str;
while (cin >> str)
{
if (str[0] == 'S')break;
else if (str[0] == 'E')
{
int number;
cin >> number;
for (int i = 1; i <= t; i++)
{
for (int j = 1; j <= len; j++)
{
if (a[i][j] == number)
{
if (Myqe[i].empty()) 子队列为空是需要重新插入输出队列
{
lev.push(i);
}
Myqe[i].push(number);
}
}
}
}
else if (str[0] == 'D')
{
cout << Myqe[lev.front()].front() << " ";
Myqe[lev.front()].pop();
if (Myqe[lev.front()].empty()) ///子队列为空,需要从输出队列中出来;
{
lev.pop();
}
}
}
return 0;
}