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 2Sample Output:
YES NO NO YES NO
简单的模拟堆栈的活动,判断YES or NO。作为堆栈的练习。用数组和结构体皆可,数组简单一些。所以在这里传一个结构体做CODE。
#include<stdio.h> #include<stdlib.h> int I = 0; typedef struct stack{ int a; struct stack* next; }Stack; Stack* Free(Stack* p); int pop(Stack*p); int IsFull(Stack* p); Stack* push(Stack* p,int value); int main(){ int m,n,k; int i,j,t = 1; scanf("%d %d %d",&m,&n,&k); int list[k][n]; for(i = 0;i<k;i++) for(j = 0;j<n;j++) scanf("%d",&list[i][j]); // 创建堆栈 Stack *SP; SP = (Stack*)malloc(sizeof(Stack)); SP->next = NULL; SP->a = 0; // 进出栈 for(i = 0;i<k;Free(SP),t = 1,i++){ for(j = 0;j<n;j++){ int Pi = list[i][j]; if(IsFull(SP)){ push(SP,t); t++; } if(!IsFull(SP)&&Pi<SP->next->a){ printf("NO\n"); break; } while(!IsFull(SP)&&Pi>SP->next->a){ push(SP,t); t++; if(I>m){ printf("NO\n"); goto out; } if(t>n) t = 1; } if(!IsFull(SP)&&Pi == SP->next->a){ pop(SP); if(j==n-1) printf("YES\n"); } } out: ; } return 0; } int pop(Stack*p){ int t; Stack* New; if(IsFull(p)){ printf("\nkong\n"); return 0; } else{ New = p->next; p->next = New->next; t = New->a; free(New); I--; return t; } } int IsFull(Stack* p){ return (p -> next == NULL); } Stack* push(Stack* p,int value){ I++; Stack *New; New = (Stack*)malloc(sizeof(struct stack)); New->a = value; New->next = p->next; p->next = New; return p; } Stack* Free(Stack* p){ while(p->next!=NULL) pop(p); return p; }