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
这道题的总体思路就是:对于每一待检测序列,用实际的栈操作对其进行模拟:
若当前栈顶和序列当前第一位相同则应出栈,否则只能入栈;
每次出栈后,根据待测序列把能出的都出完;
每次入栈后,重复第一步,再判断当前栈顶和序列当前第一位是否相同;
这是以“试图完全模拟待测序列”为目的的做法,在这个过程中如果发现哪里不对劲则说明该待测序列是无法做到的。
我们的方法就是先乐观地认为当前序列是可以实现的,于是用栈对其进行模拟。但是如果在模拟中发现了任何不对劲,我们就立即否定它。
所谓不对劲指的就是:应该出栈但栈空;应该入栈但栈满。
My answer:
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define ERROR -999
bool push(int x, int m);
int pop();
bool IsEmpty();
int gettop();
void clear();
int stack [1001];
int* top = stack - 1;
int main(void)
{
bool flag = true;
int m, n, k, i, j, element;
scanf("%d %d %d", &m, &n, &k);
int* a = (int*)malloc(n * sizeof(int));
for (i = 1; i <= k; i++) {//对每一行输入
for (j = 0; j <= n - 1; j++) {//被测序列存于数组a
scanf("%d", &a[j]);
}
for (element = 1, j = 0; element <= n; element++) {//依次将123..入栈
if (!push(element, m)) {
flag = false; break;
}
if (element == a[j]) {//入栈后若发现栈顶==a的第一个未匹配元素 则出栈
j++;
if (pop() == ERROR) {
flag = false; break;
}
//之后持续出栈直到栈顶 != a的第一个未匹配元素
while (gettop() != ERROR && gettop() == a[j]) {
j++;
if (pop() == ERROR) {
flag = false; goto out;
}
}
}
}
out:
if (!IsEmpty()) flag = false;
//做判断并准备下一次循环
if (!flag) {printf("NO\n"); clear(); flag = true; }
else { printf("YES\n"); clear(); flag = true; }
}
return 0;
}
bool push(int x, int m)
{
if (top == stack - 1 + m)return false;
else {
*(++top) = x; return true;
}
}
int pop()
{
if (top == stack - 1)return ERROR;
else return *(top--);
}
bool IsEmpty()
{
if (top == stack - 1)return true;
else return false;
}
int gettop()
{
if (IsEmpty())return ERROR;
else return *top;
}
void clear()
{
top = stack - 1;
return;
}