本题我写了好久并且写得麻烦了。
Question:
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
Idea:
造一个栈,造一个数组并配上指针记录1~N被压入的情况;每读一个数,通过指针判断该数有没有被压入,是则pop并检验,否则压入一个数。
Code:
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define ERROR -1
typedef int Position;
typedef int ElementType;
typedef struct SNode *PtrToSNode;
struct SNode
{
ElementType *Data;
Position Top;
int MaxSize;
};
typedef PtrToSNode Stack;
Stack CreateStack(int MaxSize)
{
Stack S = (Stack)malloc(sizeof(struct SNode));
S->Data = (ElementType *)malloc(sizeof(ElementType) * MaxSize);
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))
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))
return ERROR;
else
return S->Data[(S->Top--)];
}
int main(void)
{
int M, N, K;
scanf("%d%d%d", &M, &N, &K);
Stack S = CreateStack(M);
for (int i = 0; i < K; i++)
{
int left = N; //待匹配元素个数
ElementType all[N + 1]; //建立待压入元素数组
for (int j = 0; j < N + 1; j++) //初始化待压入元素数组
all[j] = j + 1;
ElementType *ptr = all; //记录待压入元素
ElementType num; //欲弹出元素
scanf("%d", &num);
while (left)
{
if (*ptr <= num)
{
if (!Push(S, *ptr++))
break;
}
else
{
if (Pop(S) != num)
break;
left--;
if (left)
scanf("%d", &num);
}
}
if (left == 0)
printf("YES\n");
else
{
left--;
while (left) //清空本次键盘输入缓冲区
{
ElementType tmp;
scanf("%d", &tmp);
left--;
}
/* 一开始没写这几行,发现本应是YES的行放到NO的行下面结果就会是NO */
printf("NO\n");
}
S->Top = -1; //清空栈
}
return 0;
}
在网上查了一下,是可以有更简单的思路的:直接比较栈顶元素和读入元素大小,前者大则失败,两者相等则检查下一个,后者大则压入一个元素。