02-线性结构4 Pop Sequence
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
这道题刚开始没有思路,借鉴了网上其他人的想法:
以判断序列 3 2 1 7 5 6 4是否可能为例
先假设这个序列可能,模拟这个序列生成过程,如果生成过程与题目条件一致,则序列存在,否则不存在。
首先我想要3!一看堆栈里面啥都没有,只能往里面放,第一次只能放1,发现1不等于3,那就再往里面放2,还不等于,那就放3,哎,等于啦!把3拿出来,再看我们假设成立的序列,该2了,我们一看栈顶是2,把2拿出来,同理,把1拿出来,这时候我们需要7了,栈里面没东西了,继续往里面加,加4,不行,加5,不行,加6,不行,加7,哎可以啦,把7拿出来,然后下一个需要的是5,发现栈顶是6,不一样,继续往栈里面放,发现没东西放了,而我们现在只能拿6,达不到我们假设序列的要求,所以我们假设的序列是失败的!
综上分析:我们相当于是对假设序列的每个元素逐一分析,同时模拟入栈过程,判断每个元素是否能被堆栈返回有一个不能返回,则失败。
原文链接:https://blog.csdn.net/solitarycccc/article/details/102874048
结合上述思路编写C语言代码如下:
#include <stdio.h>
#include <stdlib.h>
struct Sta //堆栈
{
int *data;
int top;
int maxsize;
};
typedef struct Sta * Stack;
void push(int n, Stack S);
int pop(Stack S);
int main()
{
int m, n, kl; //m是堆栈容量,n是数字,kl是输入行数
scanf("%d %d %d", &m, &n, &kl);
int i, j, k = 1;
int a[1000];
//创建堆栈
Stack S;
S = (Stack)malloc(sizeof(struct Sta));
S->maxsize = m;
S->data = (int *)malloc(m * sizeof(int));
int yes[1000]; //记录各行输入是否可能,如果可能为1,不可能为0。初始化均为1。
for (i = 0; i < kl; i++)
{
yes[i] = 1;
}
for (i = 0; i < kl; i++) //行循环
{
for (j = 0; j < n; j++)
{
scanf("%d", &a[j]);
}
k = 1;
S->top = -1; //堆栈起始为空
for (j = 0; j < n; j++) //每一行内部循环,判断该行是否可能
{
if (S->top == -1) //当堆栈为空时,就向堆栈内压入数字,直至压入a[j]
{
for (; k <= a[j]; k++) //之前使用过的数字不再使用,所以k的值在变化
{
push(k, S);
if (S->top > S->maxsize - 1)
{
yes[i] = 0;
break;
}
}
k--;
pop(S);//将a[j]弹出
}
//堆栈不空
else {
if (S->data[S->top] == a[j]) { pop(S); } //判断栈顶数字是否等于a[j]
else
{
if (k < n) //判断数字是否被用尽,是否有剩余数字可压入堆栈
{
if (S->top == S->maxsize - 1) { yes[i] = 0; } //堆栈满了,无法再压入数字
else {
while (S->top < S->maxsize - 1)
{
push(++k, S);
if (S->data[S->top] == a[j]) { pop(S); break; }//压入数字直到数字与a[j]相同
}
if (S->top == S->maxsize - 1) { yes[i] = 0; }//在压入数字与a[j]相同之前堆栈已满
}
}
else { yes[i] = 0; }
}
}
if (yes == 0) { break; }
}
}
for (i = 0; i < kl; i++)
{
if (yes[i] == 0) { printf("NO\n"); }
else { printf("YES\n"); }
}
return 0;
}
void push(int n, Stack S)
{
S->top++;
S->data[S->top] = n;
}
int pop(Stack S)
{
return S->data[S->top--];
}
代码可行,就是过程稍微有点麻烦,整体逻辑也有点混乱。。。