题意
按照1..N
的顺序入栈,问题目要问的序列是否可以通过入栈出栈(栈的长度是有限的)的操作来获得
思路
- 手动模拟
1..N
进栈的过程,同时进行判断,向要求检查的序列靠拢,在想要检查的序列中设置光标cur = 0
,比如想要检查的是1 2 3 4 5
,那么第一次入栈的时候我们入栈1
,检查栈顶元素是否等于cur
指向的元素1,如此反复。 - ⚠️
- 注意栈的容量大小是有限制的,在模拟的时候要注意检查
- 模拟结束之后栈中可能还有元素,需要再次依次出栈检查看是否符合。
#include <cstdio>
#include <vector>
#include <algorithm>
#include <iostream>
using namespace std;
const int MAXN = 1010;
int a[1010];
int stack[1010], top = -1;
int main()
{
int capacity, seq_len, queries;
cin >> capacity >> seq_len >> queries;
for(int i=0;i<queries;i++)
{
for(int j=0;j<seq_len;j++) cin >> a[j];
int cur = 0;
bool legal = true; //合法与否的判断标志
top = -1;
for(int j=1;j<=seq_len;j++) //模拟1..N的入栈过程
{
stack[++top] = j;
if(top >= capacity) //检查栈里的元素个数是否超过容量
{
legal = false;
break;
}
while(top >= 0 && stack[top] == a[cur])
{
top--;
cur++;
}
}
while(cur <= seq_len)
{
if(stack[top] != a[cur])
{
legal = false;
break;
}else{
top--;
cur++;
}
}
if(!legal)
cout << "NO
";
else cout << "YES
";
}
return 0;
}