跳到正文

题解

题解:SP28306 ADAQUEUE - Ada and Queue

yangziteng2728约 3 分钟
原文
文章信息与版本

文章信息

收录
2026年8月12日
更新
2026年11月11日
篇幅
约 3 分钟
题目
SP28306

版本

  1. v1当前

思路

题目要求维护双端队列,支持多种操作,包含翻转指令。

若直接调用函数翻转队列,时间复杂度过高无法通过大数据。

我们使用布尔标记 ff 模拟逻辑翻转,不改动队列内部元素:

f=0f=0:队列正常状态;

f=1f=1:队列处于逻辑翻转状态。

代码

C++
#include<bits/stdc++.h>
using namespace std;
deque <int> a;
int main() {
	ios_base::sync_with_stdio(0);
	cin.tie(0);
	cout.tie(0);
	int n;
	cin >> n;
	string s;
	int m;
	bool f = 0;
	while(n--){
		cin >> s;
		if(s == "back"){
			if(f == 0){
				if(a.empty()){
					cout << "No job for Ada?" << endl;
					continue;
				}
				cout << a.back() << endl;
				a.pop_back();
			}else{
				if(a.empty()){
					cout << "No job for Ada?" << endl;
					continue;
				}
				cout << a.front() << endl;
				a.pop_front();
			}
		}
		if(s == "front"){
			if(f == 0){
				if(a.empty()){
					cout << "No job for Ada?" << endl;
					continue;
				}
				cout << a.front() << endl;
				a.pop_front();
			}else{
				if(a.empty()){
					cout << "No job for Ada?" << endl;
					continue;
				}
				cout << a.back() << endl;
				a.pop_back();
			}
		}
		if(s == "reverse"){
			if(f == 0){
				f = 1;
			}else{
				f = 0;
			}
		}
		if(s == "push_back"){
			cin >> m;
			if(f == 0){
				a.push_back(m);
			}else{
				a.push_front(m);
			}
		}
		if(s == "toFront"){
			int m;
			cin >> m;
			if(f == 0){
				a.push_front(m);
			}else{
				a.push_back(m);
			}
		}
	}
	return 0;
}
原文