Given a stack which can keep M numbers at most. Push N numbers in the order of 1, 2, 3, ..., Nand 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
个人分析:这道题考察堆栈的基本操作(入栈出栈),题目要求,在入栈增序(123...)的前提下,判断一系列出栈样例,若样例是可能获得的出栈样例则输出YES,否则输出NO。菜鸡第一个想法,就是自己先手动试试,怎样的出栈pop序列是不可能的,如图:
嗯,给它想了一个很霸气的名字——动态出入栈,也就是根据所需判断的样例进行入栈和出栈操作,从而判断样例是否符合条件。时间有点晚,菜鸡忙着写完博客去学习(其实是吃鸡),这就不多废话了,上代码!!
#include<stdio.h> #include<stdlib.h> #define Max 1000 //采用链表存储堆栈 typedef struct Stack *List; struct Stack{ int data; List next; }; bool IsEmpty(List L) { return(L->next==NULL); } bool Push(int size,List L1,int data) { int cnt=0; List p=L1; while(p->next!=NULL) { cnt++; p=p->next; } if(cnt>=size) { return false; } else { List T; T=(List)malloc(sizeof(struct Stack)); T->data=data; T->next=L1->next; L1->next=T; return true; } } void Pop(List L2) { List curr; curr=L2->next; L2->next=curr->next; free(curr); } int main() { //size堆栈大小,number需入栈元素个数,exam测试样例数目,sample测试数据 int size,number,exam,sample; scanf("%d %d %d\n",&size,&number,&exam); int FLAG[Max]={0}; //FLAG[]记录每个测试样例的flag,即记录每个测试样例是否符合题目条件 for(int i=0;i<exam;i++) { List S; S=(List)malloc(sizeof(struct Stack)); S->next=NULL; int flag=0; //判断输入样例是否符合条件,不符合为1,符合为0 int t=1; for(int j=0;j<number;j++) { //动态入栈,根据输入序列控制入栈出栈 if(IsEmpty(S)) //同时判断输入序列是否符合pop(出栈)规则 { Push(size,S,t); t++; } scanf("%d",&sample); List temp=S->next; while(temp->data<sample) { if(!Push(size,S,t)) { flag=1; break; } else { temp=S->next; } t++; } if(temp->data==sample) { Pop(S); temp=S->next; } else if(temp->data>sample) { flag=1; } } if(!flag) FLAG[i]=0; else FLAG[i]=1; getchar(); } for(int i=0;i<exam;i++) { if(FLAG[i]) printf("NO\n"); else printf("YES\n"); } return 0; }
测试结果:
OKOKOK,菜鸡要开始今天的happy time了!!吃鸡的吃鸡,王者荣耀的王者荣耀!!GOGOGO!