题目大意:给出一个容量为M的栈,将数字1~N依次执行Push和Pop操作,判断给出的序列是否可能是Pop序列。
直接用STL中的栈进行模拟,对给出的序列进行遍历,如果当前数字大于栈顶元素或栈空,则执行压栈操作,从上次被压入的最后一个数+1开始,一直到当前数字,然后pop,持续判断栈的大小是否超过M。如果当前数字小于栈顶元素,则不可能。当整个序列遍历完后,stack应为空,否则也是不可能的序列。
AC代码:
#include <iostream>
#include <vector>
#include <cstdio>
#include <stack>
using namespace std;
bool judge(vector<int> &v, int M)
{
stack<int> st;
int lastPush = 0;
for (int i = 0; i < v.size(); ++i)
{
if(st.empty() || st.top() <= v[i])
{
for (int j = lastPush + 1; j <= v[i]; ++j)
{
st.push(j);
lastPush = j;
if(st.size() > M) return false;
}
}
else return false;
st.pop();
}
if(!st.empty()) return false;
return true;
}
int main()
{
int M, N, K;
cin >> M >> N >> K;
for (int query = 0; query < K; ++query)
{
vector<int> v(N);
for (int i = 0; i < N; ++i)
scanf("%d", &v[i]);
if(judge(v, M)) printf("YES\n");
else printf("NO\n");
}
return 0;
}
该博客介绍了PAT(A1051)编程题中关于栈的Pop序列问题的解决方法。通过使用STL栈进行模拟,遍历序列,判断数字与栈顶元素的关系来决定是否执行压栈和弹栈操作。如果序列遍历完后栈为空且过程中未超过栈的容量M,则序列可能;否则,不可能。
213

被折叠的 条评论
为什么被折叠?



