B3616 【模板】队列
别问我为什么这一道题怎么跟上一题那么像呢(问就是没有)
B3616 【模板】队列
1.题目简介:
题目描述 请你实现一个队列(queue),支持如下操作:
push(x):向队列中加入一个数
x。 pop():将队首弹出。如果此时队列为空,则不进行弹出操作,并输出 ERR_CANNOT_POP。 query():输出队首元素。如果此时队首为空,则输出 ERR_CANNOT_QUERY。 size():输出此时队列内元素个数。 输入格式 第一行,一个整数 n,表示操作的次数。 接下来 n 行,每行表示一个操作。格式如下: 1 x,表示将元素 x 加入队列。 2,表示将队首弹出队列。 3,表示查询队首。 4,表示查询队列内元素个数。 输出格式 输出若干行,对于每个操作,按「题目描述」输出结果。
每条输出之间应当用空行隔开。
2.队列是什么:
队列和栈相反:栈是最先进的最后出,栈是最后进的最先出;
队列是最先进的最先出,栈是最后进的最后出。
队列类似于超市出口处排队结算,银行等待窗口办理业务等,就像现实生活中的排队。
因此我们可以用两种方法实现
1.数组写法
#include<iostream>
using namespace std;
int lis[100001];
int h = 0, t = -1;
int n;
int m;
int x;
int main(){
cin >> n;
for(int i = 1;i <= n;i++){
cin >> m;
if(m == 1){
cin >> x;
t++;
lis[t] = x;
}
else if(m == 2){
if(t - h + 1 == 0){
cout << "ERR_CANNOT_POP" << endl;
}
else{
h++;
}
}
else if(m == 3){
if(t - h + 1 == 0){
cout << "ERR_CANNOT_QUERY" << endl;
}
else{
cout << lis[h] << endl;
}
}
else if(m == 4){
cout << (t - h) + 1 << endl;
}
}
return 0;
}
2.直接使用对列
#include<iostream>
#include<queue>
using namespace std;
queue <int> q;
int n;
int m;
int x;
int main(){
cin >> n;
for(int i = 1;i <= n;i++){
cin >> m;
if(m == 1){
cin >> x;
q.push(x);
}
else if(m == 2){
if(q.empty()){
cout << "ERR_CANNOT_POP" << endl;
}
else{
q.pop();
}
}
else if(m == 3){
if(q.empty()){
cout << "ERR_CANNOT_QUERY" << endl;
}
else{
cout << q.front() << endl;
}
}
else if(m == 4){
cout << q.size() << endl;
}
}
return 0;
}