题目
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.
思路
在每个待查序列中,对每一个数字判断:
- 该数字大于前一个数字——进行了Push及Pop操作(对小于该等于数字且未进栈的数字Push,更改现存数量)
- 该数字小于前一个数字——进行了Pop操作(判断该数字否与当前栈顶数字相同,修改当前堆栈数字数量)
- 记录操作后堆栈内数字数,判断是否超过堆栈容量
代码
#include<stdio.h>
#include<stdlib.h>
typedef struct stack* ptrl;
struct stack{
int data;
ptrl next;
};
~~栈操作集~~
ptrl createstack()
{
ptrl s;
s=(ptrl)malloc(sizeof(struct stack));
s->next=NULL;
return s;
}
ptrl push(ptrl s,int data){
ptrl tmp;
tmp=(ptrl)malloc(sizeof(struct stack));
tmp->data=data;
tmp->next=s->next;
s->next=tmp;
return s;
}
int pop(ptrl s)
{
ptrl t;
int output;
t=s->next;
output=t->data;
s->next=t->next;
free(t);
return output;
}
int main()
{
int M,N,K;
scanf("%d%d%d",&M,&N,&K);
int result[K];
for(int i=0;i<K;i++){
int s_max=0;//s_max-进入过堆栈的最大数据
int pre_data=0;
int dynamic=0;//堆栈现有数据计数 <=M
int flag=1;/*yes=1 or no=0 */
ptrl stack;
stack=createstack();
for(int j=0;j<N;j++)
{
int data;//输入的数据
scanf("%d",&data);
if(flag==1){ /*flag未出现0即继续进行*/
if(data>pre_data){/*大于前一个数据的话,push后pop ,renew s_max, 溢出返回no */
int amount=data-s_max;//每一次的push次数
int push_data=s_max;//push大于s_max小于data的数据
~~Push操作~~
for(int k=0;k<amount&&amount<=M;k++){
if(dynamic<=M){
stack=push(stack,++push_data);
dynamic++; }
if(dynamic>M){ flag=0;break;}//溢出,注意此处用if还是else的影响
}
if(k!=amount) flag=0;
~~pop操作~~
if(flag==1) {
int pop_data=pop(stack);
if(pop_data>s_max) {
s_max=pop_data;/*记录已经入栈的最大数字*/
dynamic--; }
pre_data=data;
}
else flag=0; }
else { //小于的话,pop
if(pop(stack)==data){pre_data=data;dynamic--;}
else flag=0; /*该数字与栈顶数字不同*/ }
}
}
if(flag==0) result[i]=0;
else result[i]=1;
}
for(int i=0;i<K;i++){
if(result[i]==0) printf("NO\n");
else printf("YES\n");
}
return 0;
}