一、题目
二、代码
#include <iostream>
#include<queue>
using namespace std;
int whi(int s, int** a, int m, int n)
{
int w = -1;
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
if (s == a[i][j])
{
w = i;
break;
}
}
}
return w;
}
int main()
{
int t;
cin >> t;
int n;
int** have = new int* [t];
for (int m = 0; m < t; m++)
{
cin >> n;
int temp;
have[m] = new int[n];
for (int i = 0; i < n; i++)
{
cin >> temp;
have[m][i] = temp;
}
}
queue<int>* answer = new queue<int>[t];
int num = 0;
int m = 0;
int p = 0;
while (1)
{
string want;
cin >> want;
if (want == "ENQUEUE")
{
int temp;
int lo;
cin >> temp;
if (num == 0)
{
answer[m].push(temp);
num++;
}
else
{
int w = whi(temp, have, t, n);
int bo = -1;
for (int i = 0; i <= m; i++)
{
lo = answer[i].front();
if (whi(lo, have, t, n) == w)
{
bo = i;
break;
}
}
if (bo == -1)
{
answer[m + 1].push(temp);
m = m + 1;
}
else
{
answer[bo].push(temp);
}
}
}
else if (want == "DEQUEUE")
{
for (int i = 0; i < t;)
{
if (answer[i].empty())
{
i++;
}
else
{
if (p == 0)
{
cout << answer[i].front();
answer[i].pop();
p++;
break;
}
else
{
cout << " " << answer[i].front();
answer[i].pop();
break;
}
}
}
}
else if (want == "STOP")
{
break;
}
}
return 0;
}
总结
在该题中,运用队列的仅有后面的插入与输出,前面的部分可以用二维数组表示。问题主要在插入的数属于队列组中的哪一个队列。判断时只需要与每个队列的第一个或最后一个元素比较即可,队列不适用遍历且不需要遍历。