朋友队列.
原创
©著作权归作者所有:来自51CTO博客作者yitahutu79的原创作品,请联系作者获取转载授权,否则将追究法律责任
题目描述
每当在食堂排队的时候,总是有熟人直接插队,对于这种队列,我们称之为朋友队列。
现在有 n 组朋友关系,当某人入队时,当前队列中有朋友关系的人在排队时,他会直接排在他所在的朋友关系的末尾;否则他会排到队伍的最后面。现在给出朋友关系和入队出队的指令,输出出队的顺序。
输入
第一行输入一个整数 n,表示有 n(1≤n≤1000) 组朋友关系。
接下来 n 行,每行第一个数为 m(1≤m≤1000),表示这组朋友关系的人数,紧跟着 m 个数表示关系当中人的编号。
接下来 x 行表示操作,ENQUEUE y 表示将 y 入队,DEQUEUE 表示出队。
当读入 STOP 时程序结束。
所有人的编号 x∈[0,999999],操作数量不会超过 200,000 个。
输出
对于每一次出队操作输出一个数,表示出队的人的编号。
样例输入
2
3 101 102 103
3 201 202 203
ENQUEUE 101
ENQUEUE 201
ENQUEUE 102
ENQUEUE 202
ENQUEUE 103
ENQUEUE 203
DEQUEUE
DEQUEUE
DEQUEUE
DEQUEUE
DEQUEUE
DEQUEUE
STOP
样例输出
101
102
103
201
202
203
数据规模与约定
时间限制:1 s
内存限制:256 M
100% 的数据保证 数据合法
#include <iostream>
#include <queue>
#include <string>
#include <map>
using namespace std;
map<int, int> q_ind;
queue<int> q_main;
queue<int> q[1005];
int main() {
int n;
cin >> n;
for (int i = 0; i < n; i++) {
int m;
cin >> m;
for (int j = 0; j < m; j++) {
int a;
cin >> a;
q_ind[a] = i + 1;
}
}
string op;
while (cin >> op) {
if (op == "STOP") break;
if (op == "ENQUEUE") {
int x;
cin >> x;
q[q_ind[x]].push(x);
if (q[q_ind[x]].size() == 1) q_main.push(q_ind[x]);
}
else {
cout << q[q_main.front()].front() << endl;
q[q_main.front()].pop();
if (q[q_main.front()].empty()) q_main.pop();
}
}
return 0;
}
#include <iostream>
#include <queue>
#include <string>
#include <map>
using namespace std;
#define MAX_N 1000
map<int, int> q_ind;
queue<int> q_main;
queue<int> q[MAX_N + 5];
int main() {
int n;
cin >> n;
for (int i = 1; i <= n; i++) {
int m;
cin >> m;
for (int j = 0; j < m; j++) {
int a;
cin >> a;
q_ind[a] = i;
}
}
string op;
op.resize(20);
while (scanf("%s", &op[0]) != EOF) {
if (strcmp(op.c_str(),"STOP")==0) break;
if (strcmp(op.c_str(), "ENQUEUE") == 0) {
int x;
scanf("%d", &x);
q[q_ind[x]].push(x);
if (q[q_ind[x]].size() == 1) q_main.push(q_ind[x]);
}
else {
printf("%d\n", q[q_main.front()].front());
q[q_main.front()].pop();
if (q[q_main.front()].empty()) q_main.pop();
}
}
return 0;
}