Given a stack which can keep MM 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 MM 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): MM (the maximum capacity of the stack), NN (the length of push sequence), and KK (the number of pop sequences to be checked). Then KK lines follow, each contains a pop sequence of NN 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、已知栈的大小、入栈的元素顺序和数量、出栈序列,判断出栈序列是否正确(入栈顺序很重要,如果有7个元素,顺序是1,2,3,4,5,6,7)
2、可以根据已知的条件来模拟一个入栈出栈的过程:
比如3,2,1,7,5,6,4;
遇到3,说明1,2,3都按顺序入栈了,根据出栈序列,3,2,1分别按顺序出栈
然后碰到7,说明4,5,6,7已按顺序入栈,然后7出栈;这时候栈顶是6,不可能是5出栈,因此这个序列是错误的。
注意:具体实现的时候,用一个循环来检测出栈序列的每一个元素,如果它大于栈顶的元素(栈顶放个哨兵0,便于比较),那么就把它之前大于栈顶的元素一一入栈(直到全部入栈或者栈满)。然后检查它是否与现在的栈顶元素相同,相同则把栈顶元素出栈,否则就是个错误序列。然后继续下一个循环,全部循环做完都没出错,那么就是正确的序列。
#include <stdio.h>
#include <stdlib.h>
//栈的结构数组表示
#define Error -1;
typedef int Position;
typedef int ElementType;
typedef struct SNode *Stack;
struct SNode {
ElementType * Data;
Position Top;
int MaxSize;
};
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("stack is full");
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("stack is empty");
return Error;
}
else {
return S->Data[S->Top--];
}
}
void StackClear( Stack S ){
S->Top = -1;
}
//根据出栈顺序,模拟整个 入/出栈过程 ;
bool check( int arr[], int M, int N) {
int i = 0, num = 1;
//多开辟一位,放个哨兵0,方便比较
Stack T = CreateStack(M + 1);
Push(T, 0);
//碰到arr[i], 就将它以及它之前的数都入栈,直到 入栈完毕 或 栈满
while( i < N ){
while(arr[i] > T->Data[T->Top] && !IsFull(T))
Push(T, num++);
//比较arr[i]与栈顶元素是否相同,相同抛出,不相同说明这个序列不可能;
if(arr[i++] == T->Data[T->Top])
Pop(T);
else
return false;
}
return true;
}
int main(){
int N, M, K, t;
int *arr;
scanf("%d %d %d", &M, &N, &K); //顺序别搞错,错误原因
arr = (int *)malloc(N * sizeof(int));
for(int i = 0; i < K; i++){
for(int j = 0; j < N; j++){
scanf("%d", &arr[j]);
}
if( check(arr, M, N) )
printf("YES\n");
else
printf("NO\n");
}
system("pause");
return 0;
}