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
思路很简单:将不大于当前出栈的元素全部入栈,再模拟出栈过程,若某刻栈顶元素比出栈元素要大,证明该出栈元素错误出栈。(ps)栈满后入栈报错
#include <stdio.h>
#include <malloc.h>
#include <stdbool.h>
#define ERROR -1
#define MaxNum 1005
typedef int ElementType;
typedef int Position;
struct SNode {
ElementType *Data; /* 存储元素的数组 */
Position Top; /* 栈顶指针 */
int MaxSize; /* 堆栈最大容量 */
};
typedef struct SNode *Stack;
Stack CreateStack( int MaxSize )
{
Stack S = (Stack)malloc(sizeof(struct SNode));
S->Data = (ElementType *)malloc(MaxSize * sizeof(ElementType));
S->Top = -1;
S->MaxSize = MaxSize;
return S;
}
bool IsFull( Stack S )
{
return (S->Top == S->MaxSize-1);
}
bool Push( Stack S, ElementType X )
{
if ( IsFull(S) ) {
//printf("堆栈满");
return false;
}
else {
S->Data[++(S->Top)] = X;
return true;
}
}
bool IsEmpty( Stack S )
{
return (S->Top == -1);
}
ElementType Pop( Stack S )
{
if ( IsEmpty(S) ) {
//printf("堆栈空");
return ERROR; /* ERROR是ElementType的特殊值,标志错误 */
}
else
return ( S->Data[(S->Top)--] );
}
ElementType Top(Stack S){
if(IsEmpty(S)){
//printf("堆栈空");
return ERROR;
}
else
return S->Data[S->Top];
}
int isPopSequence(int* pushSeq,int* popSeq,Stack S,int SeqLen){
int push_i=0,pop_i=0;
S->Top=-1;
while(pop_i<SeqLen){
if(Top(S)<popSeq[pop_i]){
while(Top(S)<popSeq[pop_i]){
// if(!Push(S,pushSeq[push_i++])) return 0;
if(IsFull(S)) return 0;
Push(S,pushSeq[push_i++]);
}
}
else if(Top(S)==popSeq[pop_i]){
Pop(S);
pop_i++;
}
else{
return 0;
}
}
if(pop_i==SeqLen)
return 1;
}
int main()
{
freopen("1.txt","r",stdin);
int M,N,K;
int pushSeq[MaxNum];
int popSeq[MaxNum]={0};
scanf("%d %d %d",&M,&N,&K);
for(int a=0;a<N;a++)
pushSeq[a] = a+1;
Stack S=CreateStack(K);
for(;K>0;K--){
for(int i=0;i<N;i++){
scanf("%d",&popSeq[i]);
}
if(isPopSequence(pushSeq,popSeq,S,N)==1)
printf("YES\n");
else
printf("NO\n");
}
return 0;
}