0
点赞
收藏
分享

微信扫一扫

02-线性结构4 Pop Sequence (25 分)

卿卿如梦 2022-03-17 阅读 71

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

显而易见,模拟栈即可,附分析过程,如图:

代码如下:

#include <stdio.h>
#include <malloc.h>
typedef struct stack
{
	int *arr;
	int top;
	int max;
}* Stack;  
int queue[1001],goal[1001];//原始序列与目标序列 
Stack Create(int m)//创建一个栈 
{
	Stack s;
	s=(Stack)malloc(sizeof(struct stack));
	s->arr=(int *)malloc(sizeof(int )*m);
	s->top=-1;
	s->max=m;
	return s;
}
int isfull(Stack s)//栈的相关操作 
{
	if(s->top==s->max-1)
	{
		return 1;
	}
	else
	{
		return 0;
	 } 
}
int pop(Stack s)
{
	if(isempty(s))
	{
		return 0;
	}
	else
	{
		int temp=s->arr[s->top];
		s->top--;
		return temp;
	}
}
int isempty(Stack s)
{
	if(s->top==-1)
	{
		return 1;
	}
	else
	{
		return 0;
	}
}
void push(Stack s,int sum)
{
	if(!isfull(s))
	{
		s->top++;
		s->arr[s->top]=sum;
	}
	return ;
}
int Find(int *queue,int *goal,int m,int n)//起判断作用的主功能函数 
{
	Stack s;
	int p1=0,p2=0;
	s=Create(m);
	while(p2<n)//p1代表原始数列下标,p2代表目标数列下标 
	{
		if(p1==n)//会出现这样一种情况,即p2没有遍历完,但是p1跑完了,为了让其不越界,让他始终处于最后一个位置 
		{
			p1--;
		}
		if(goal[p2]>queue[p1])//每次先判断栈是否满,满的话直接不符合,return 0; 
		{
			if(isfull(s))//下面分情况,目标大,则原始数列元素进栈,下标往后移;
			             //相等则进栈后出栈,相当于不做,所以直接两个下标加加即可; 
			             //都不满足那就是原始大于目标的情况,看栈顶元素与目标相不相同,相同则pop,不然那就是不符合,return 0; 
			{
				return 0;
			}
			else
			{
				push(s,queue[p1]);
			}
			p1++;
		}
		else if(goal[p2]==queue[p1])
		{
			if(isfull(s))
			{
				return 0;
			}
			else
			{
			    p1++;
				p2++;				
			}
		}
		else
		{
			if(goal[p2]==s->arr[s->top])
			{
				pop(s);
				p2++;
			}
			else
			{
				return 0;
			}
		}
	}
	return 1;
}
int main()//程序框架 
{
	int M,N,K,i;
	scanf("%d%d%d",&M,&N,&K);
	for(i=0;i<N;i++)
	{
		queue[i]=i+1;
	}
	while(K--)
	{
		for(i=0;i<N;i++)
		{
			scanf("%d",&goal[i]);
		}
		if(Find(queue,goal,M,N))
		{
			printf("YES\n");
		}
		else
		{
			printf("NO\n");
		}
	}
	return 0;
}
举报

相关推荐

0 条评论