02-线性结构4 Pop Sequence(25分)
题目描述
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
题目链接
思路
这题是对线性表中堆栈的应用,查找合法的出栈顺序,我一开始没有任何思路,在看了别人的题解后,最后做出来了,这里附上 7-33 Pop Sequence (25分)(完整模拟思路+极短代码),里面的思路可以借鉴。其实就是对堆栈的入栈和出栈进行模拟,Pop Sequence 中的每个元素都是最后一个出栈的元素。
1. 创建堆栈:
由于本题有了相应的限制,所以我简写了堆栈的代码,包括入栈,出栈等操作,更多的栈功能的实现可以参见 PTA 上 6-7 在一个数组中实现两个堆栈 和 6-2 顺序表操作集,代码如下:
#define MAXSIZE 1001 // 定义栈的最大容量
// 定义栈结构体
typedef struct Stack {
int data[MAXSIZE]; // 存储栈中元素的数组
int top; // 栈顶指针
int capacity; // 栈的容量
} stack;
// 初始化栈函数
stack *stackInit(int size) {
stack *obj = (stack *)malloc(sizeof(stack));
obj->top = -1; // 初始化栈顶指针为-1,表示栈为空
obj->capacity = size; // 设置栈的容量
return obj;
}
// 压栈操作函数
void push(stack *stk, int val) {
stk->data[++stk->top] = val; // 先将栈顶指针加1,然后将值压入栈顶
}
// 出栈操作函数
void pop(stack *stk) {
--