1051. Pop Sequence (25)

来源:互联网 发布:java 界面开发 编辑:程序博客网 时间:2024/05/21 12:13



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


这个题刚开始完全没有思路,后来看了别人写的博客,发现此题并不难。打个比喻,如果要检查一辆车是否合格,肯定是每个零件都要检查一遍(这个比喻不一定恰当),同样,检查一个序列是否可由条件生成,那么就检查一下这个序列的每个元素是否可生成。所以问题划归为检查一个数。

算法的定义是有限个有序的步骤解决一个问题,所以很多时候,走出第一步就成功了一般。

具体代码如下:

/*************************************************************************> File Name: 1051.c> Author: > Mail: > Created Time: 2016年12月22日 星期四 23时39分48秒 ************************************************************************/#include<stdio.h>#include <malloc.h>int main(){    int M, N, K;    int popEle, pushEle;    int i, j, k = 1;    int rear = -1;    int flag = 1;    scanf("%d%d%d", &M, &N, &K);    int* Stack = (int*)malloc(M * sizeof(int));    for (i = 0; i < K; i++) {          flag = 1;        rear = -1;        k = 1;        for (j = 0; j < N; j++) { //inspect j_th element             scanf("%d", &popEle);            if (rear != -1 && Stack[rear] == popEle) { //find it in the stack                rear -= 1;            } else {  //find in the numbers not pushed into stack                while (k != popEle && k <= N && rear < M-2) { //rear < M-2, not M-1                    Stack[++rear] = k;                    ++k;                }                if (k != popEle) {                    flag = 0;                } else {                    ++k;                }            }        }        if (flag == 1) {            printf("YES\n");        } else {            printf("NO\n");        }    }    return 0;}

编程之路,进步,再进一步!

0 0