原题
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
结尾无空行
题目理解:
考察的是堆栈的知识,LIFO(后进先出)。给出了一个1,2,... ,n的顺序序列,然后与要被check的序列比较,看顺序序列是否能通过大小为m的堆栈实现被check的序列。我的思路就是模拟堆栈的过程,首先创建一个m的堆栈,然后从check的序列的第一个元素开始,进行比较。
case 1. 栈为空or栈的顶部元素==check序列中被指向的元素。
此时,栈顶元素pop出去,指向下一个check元素
case 2.栈的顶部元素!=check序列中被指向的元素
1)此时,如果栈已经满了,那么就证明没办法实现
2)栈未满,栈push进下一个元素
为了图省事,把被check的序列和栈写成了一个struct~
答案(AC)
#include <stdio.h> #include <stdlib.h> struct Stack { int *array; int maxsize; int top; int cnt; }; typedef struct Stack *stack; stack Createstack(int n); void ReadStack(stack S); void pop(stack S); void push(stack S); int Isfull(stack S); void RenewStack(stack S); int main() { int n, m, k; int i, j; scanf("%d %d %d", &m, &n, &k); /* m (the maximum capacity of the stack), n (the length of push sequence), k (the number of pop sequences to be checked). */ stack S1 = Createstack(m); stack S2 = Createstack(n); //S2 is to be checked for (i = 0; i < k; i++) { ReadStack(S2); while (S2->top < n) { if (S1->top >= 0 && S1->array[S1->top] == S2->array[S2->top]) { S2->top++; pop(S1); } else { if (Isfull(S1)) break; else push(S1); } } if (S2->top == n) printf("YES\n"); else printf("NO\n"); RenewStack(S1); } return 0; } stack Createstack(int n) { int i; stack S = (stack)malloc(sizeof(struct Stack)); S->array = (int *)malloc(sizeof(int) * n); S->maxsize = n; S->cnt = 1; S->top = -1; return S; } void ReadStack(stack S) { int i; for (i = 0; i < S->maxsize; i++) { scanf("%d", &S->array[i]); } S->top = 0; } void pop(stack S) { S->top--; } void push(stack S) { S->array[++S->top] = S->cnt++; } int Isfull(stack S) { if (S->top == S->maxsize - 1) return 1; else return 0; } void RenewStack(stack S){ S->top=-1; S->cnt=1; }