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
 1 #include <stdlib.h>
 2 #include <cstdio>
 3 const int maxsize = 1001;
 4 struct SNode {
 5     int* data;
 6     int top;
 7     int MaxSize;
 8 };
 9 
10 typedef struct SNode *Stack;
11  
12 Stack CreateStack( int MaxSize ) {
13     Stack s = (Stack) malloc(sizeof(struct SNode));
14     s->data = (int* ) malloc(MaxSize * sizeof(int));
15     s->top = -1;
16     s->MaxSize = MaxSize;
17     return s; 
18 }
19 
20 bool isFull( Stack s ) {
21     return (s->top == s->MaxSize-1);
22 }
23 bool isEmpty( Stack s ) {
24     return (s->top == -1);
25 }
26 
27 bool push( Stack s, int x) {
28     if( isFull(s) ) {
29         return false;
30     }
31     else {
32         s->data[++(s->top)] = x;
33         return true;
34     }
35 }
36 
37 int pop( Stack s ) {
38     return s->data[(s->top)--];
39 }
40 
41 
42 int main() {
43     int m, n, k, a[maxsize];
44     scanf("%d %d %d", &m, &n, &k);
45     
46     while(k--) {
47         Stack s1 = CreateStack(m);
48         for(int i=0; i<n; i++) {
49             scanf("%d", &a[i]);
50         }
51         int j = 0, flag;
52         for(int i=1; i<=n; i++) {
53             flag = push(s1, i);
54             if(!flag) break;
55             while(!isEmpty(s1) && a[j] == s1->data[s1->top]) {
56                 j++;
57                 pop(s1);
58             }
59         }
60         if(flag == false) {
61             printf("NO\n");
62         }
63         else if(isEmpty(s1)) {
64             printf("YES\n");
65         }
66         else printf("NO\n");
67         
68         
69             
70         
71         
72         
73     }
74     
75     
76     
77     
78 }
AC

 

posted @ 2019-05-28 10:18  Acoccus  阅读(582)  评论(0编辑  收藏  举报