題目
思路
維護三個集合:核心棧、數字隊列、目標隊列
詳細思路見註釋
題解 C++
#include<iostream>
#include<stack>
#include<queue>
using namespace std;
int main() {
int stackSize, len, total;
cin >> stackSize >> len >> total;
for (int i = 0; i < total; i++) {
stack<int> ss;//核心棧
queue<int> in;//數字隊列
queue<int> out;//目標隊列
//輸入數字隊列
for (int i = 1; i <= len; i++) {
in.push(i);
}
//輸入目標隊列
for (int i = 0; i < len; i++) {
int t;
cin >> t;
out.push(t);
}
//模擬棧:判斷目標序列是否成立
while (true) {
if (ss.size() > stackSize) {//核心棧溢出:失敗
cout << "NO\n";
break;
}
else if (ss.size() == 0) {//核心棧爲空,則從數字隊列中取出一個放進去
ss.push(in.front());
in.pop();
}
if (ss.top() == out.front()) {//核心棧頂元素=目標隊列頭元素
ss.pop();//核心棧出棧
out.pop();//目標隊列出隊
}
else {//棧頂元素不等於目標元素
if (in.size() == 0) {//數字隊列已空:失敗
cout << "NO\n";
break;
}
ss.push(in.front());//核心棧入棧
in.pop();//數字序列出棧
}
if (out.size() == 0) {//目標隊列爲空: 成功
cout << "YES\n";
break;
}
}
}
system("pause");
}