题目
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
解题思路
本题考查的知识点是“栈push和pop的顺序是先进后出”,当栈顶元素和数列的当前的第一个元素相等时,直接将栈顶元素pop出;若不一致时,便按照自然数顺序放入元素,直到栈顶元素和当前第一个元素相等,若栈满时仍然没有找到和当前第一个元素相等的栈顶元素,那么该数列不通过栈获得。
易错点
- 注意在找到某一个元素是不可以获得的时候,不要直接跳出循环,而是要将该序列剩下的元素读完,再进行读下一串序列;
- 在每读入一串序列之前,需要先保证将栈清空,避免影响下一次判断。
代码
#include<bits/stdc++.h>
using namespace std;
int main(){
int M,N,K,i,j,k,F,temp;
scanf("%d %d %d",&N,&M,&K);//N是栈的容量,M是输入元素的个数
for (i=0;i<K;i++)//读入序列的数目
{
k = 0;
F = 0;
stack <int> s;//避免需要将栈清空,每一次都使用新的栈
for (j=0;j<M;j++)
{
scanf("%d",&temp);
if (F==0)
{
if (s.size()!=0 && temp==s.top())
s.pop();
else
{
while (s.size()<N && k<M && temp!=k){
s.push(++k);}
if (temp==s.top())//相等的没有入栈,也就不需要出栈
s.pop();
else//满了or所有元素放完了还是没有相等的
F = 1;
}
}
}
if (F==1)
printf("NO\n");
else
printf("YES\n");
}
return 0;
}