Given a stack which can keep M numbers at most. Push N numbers in the order of 1, 2, 3, …, N and pop randomly. You are supposed to tell if a given sequence of numbers is a possible pop sequence of the stack. For example, if M is 5 and N is 7, we can obtain 1, 2, 3, 4, 5, 6, 7 from the stack, but not 3, 2, 1, 7, 5, 6, 4.
Input Specification:
Each input file contains one test case. For each case, the first line contains 3 numbers (all no more than 1000): M (the maximum capacity of the stack), N (the length of push sequence), and K (the number of pop sequences to be checked). Then K lines follow, each contains a pop sequence of N numbers. All the numbers in a line are separated by a space.
Output Specification:
For each pop sequence, print in one line “YES” if it is indeed a possible pop sequence of the stack, or “NO” if not.
Sample Input:
5 7 5
1 2 3 4 5 6 7
3 2 1 7 5 6 4
7 6 5 4 3 2 1
5 6 4 3 7 2 1
1 7 6 5 4 3 2
Sample Output:
YES
NO
NO
YES
NO
本题是判断一个给定的序列是否为合法的出栈序列,入栈默认为1,2……N,栈的最大容量也已给出。
可以用栈来模拟一个出栈序列来判定是否合法。给定的一串出栈序列,分别用栈顶元素和其比较,若相等,则出栈,然后判定下一个元素。若不等,则按顺序进栈,直至相等,每比较一个数组,都检查一下栈的长度是否超过了给定的栈的最大容量,若超出,则不合法。
对于给定的N组数据,每组数据长度为K,判断的语句如下:
for (int i = 0; i < N; i++)
{
open = 1;//用来模拟入栈的元素,入栈是按1到K的顺序入栈的
is_failed = false;
for (int j = 0; j < K; j++)//每组数据有K个,进行K次循环,将数据输入并且判断
{
cin >> pop;//输入数据
while (st.size() <= M && !is_failed)//st的长度大于M时,即是不合法的出栈序列,无需继续判断,直接跳出即可,
{
if (st.empty() || pop != st.top())//栈空时判断,则直接压一个进栈,不相等时就不断压栈,直至相等。
{
st.push(open++);
}
else { st.pop(); break; }//正常情况出栈并跳出while循环
}
if (st.size() > M) is_failed = true;
完整代码如下:
#include <iostream>
#include<stack>
using namespace std;
int main()
{
stack<int> st;
int M, K, N;
cin >> M >> K >> N;
int open;
bool is_failed;
int pop;
for (int i = 0; i < N; i++)
{
open = 1;
is_failed = false;
for (int j = 0; j < K; j++)
{
cin >> pop;
while (st.size() <= M && !is_failed)
{
if (st.empty() || pop != st.top())
{
st.push(open++);
}
else { st.pop(); break; }
}
if (st.size() > M) is_failed = true;
}
if (is_failed) cout << "NO" << endl;
else cout << "YES" << endl;
while (!st.empty()) st.pop();
}
return 0;
}