美文网首页浙大数据结构公开课
02 - 线性结构 3 Pop Sequence (25 分

02 - 线性结构 3 Pop Sequence (25 分

作者: 戏之地 | 来源:发表于2016-05-08 21:44 被阅读425次

<pre>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
</pre>
<pre>

include<stdio.h>

include<malloc.h>

define MAXSIZE 1000

typedef struct SA *SP;
struct SA{
int top;
int data[MAXSIZE];
int cap;
};
//创建栈数组
SP create(int cap){
SP root ;
root=(SP)malloc(sizeof(struct SA));
root->top=-1;
root->cap=cap;
return root;
}
//入栈数组
int push(SP sp,int item){
if(sp->cap-sp->top<=1){
return 0;
}
sp->data[++sp->top]=item;
return 1;
}
//从栈数组上得到
int getTop(SP sp){
if(sp->top>=0){
return sp->data[sp->top];
}else{
return -1;
}
}
//弹出
void pop(SP sp){
sp->top--;
}
void destroySA(SP sp){
free(sp);
}
//判断这个数组序列是否为出栈序列
//入栈时,栈顶元素与出线序列数组比较
//若相同,则两者均向后加一
//参数:出栈序列,栈容量,入栈序列
//这里入栈序列用n表示,依次把n放入
int isOutOrder(int popOrder[],int cap ,int n){
int i;//i代表挨个入栈数
SP sp;
int first=0;//出栈序列的头
sp=create(cap);
for(i=1;i<=n;i++){
if(!push(sp,i)){
destroySA(sp);
return 0;
}
while(getTop(sp)==popOrder[first]){
pop(sp);
first++;
}

}
destroySA(sp);
if(first < n){
    return 0;
}
return 1;

}
int main(){
int cap,length,orders;
int i = 0,j=0;
scanf("%d%d%d",&cap,&length,&orders);
int popOrder[1000];
for(i=0;i< orders;i++){
for(j=0;j< length;j++){
scanf("%d",&popOrder[j]);

    }
    if(isOutOrder(popOrder,cap,length)){
            printf("YES\n");
    }else{
            printf("NO\n");
    }
}
return 1;

}

</pre>

相关文章

网友评论

    本文标题:02 - 线性结构 3 Pop Sequence (25 分

    本文链接:https://www.haomeiwen.com/subject/vonsrttx.html