跳到正文

算法·理论

[模板]队列的四种方法

ruiqi2012约 2 分钟
原文
文章信息与版本

文章信息

收录
2026年7月25日
更新
2026年7月25日
篇幅
约 2 分钟

版本

  1. v1当前

[模板]队列四种方法

单调队列

  • STL
C++
#include<bits/stdc++.h>
using namespace std;
queue<int>q;
int n;
int main(){
	scanf("%d",&n);
	for(int i = 1;i<=n;i++){
		int o,x;
		scanf("%d",&o);
		if(o==1){
			scanf("%d",&x);
			q.push(x);
		}
		if(o==2){
			if(q.empty()){
				cout<<"ERR_CANNOT_POP"<<endl;
			}
			else{
				q.pop();
			}
		}
		if(o==3){
			if(q.empty()){
				cout<<"ERR_CANNOT_QUERY"<<endl;
			}
			else{
				cout<<q.front()<<endl;
			}			
		}
		if(o==4){
			cout<<q.size()<<endl;
		}
	}
	return 0;
}
  • 手写
C++
#include<bits/stdc++.h>
using namespace std;
int q[10010];
int front = 1,rear = 0;
int n;
int main(){
	scanf("%d",&n);
	for(int i = 1;i<=n;i++){
		int o,x;
		scanf("%d",&o);
		if(o==1){
			scanf("%d",&x);
			q[++rear] = x;
		}
		if(o==2){
			if(front>rear){
				cout<<"ERR_CANNOT_POP"<<endl;
			}
			else{
				front++;
			}
		}
		if(o==3){
			if(front>rear){
				cout<<"ERR_CANNOT_QUERY"<<endl;
			}
			else{
				cout<<q[front]<<endl;
			}			
		}
		if(o==4){
			cout<<rear-front+1<<endl;
		}
	}
	return 0;
}
原文
存档评论3 条抓取于