PATA 1051.Pop Sequence(25)解题报告

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
作者: 陈越
单位: 浙江大学
时间限制: 400ms
内存限制: 64MB
代码长度限制: 16KB

AC代码:

//02-线性结构4 Pop Sequence(25 分)
#include<iostream>
#include<stdio.h>
using namespace std;
#define MAXSIZE 1000
typedef struct
{
	int data[MAXSIZE];
	int top;
}SqStack;

int InitStack(SqStack *s)
{
	s->top=-1;
	return 0;
}
int Push(SqStack *s,int e)
{
	if(s->top==MAXSIZE-1)
	return 1;
	s->top++;
	s->data[s->top]=e;
	return 0;
}

int Pop(SqStack *s)
{
	int e;
	if(s->top==-1)
	return 1;
	e=s->data[s->top];
	s->top--;
	return e; 
}

int main()
{
	int m,n,k,i,h;
	cin>>m>>n>>k;
	SqStack s,t;
	while(k--)
	{
		InitStack(&s);
		InitStack(&t);
		for(i=n-1;i>=0;i--)//注意i开始的位置,栈顶是最先出栈的元素 
		{
			cin>>t.data[i];
		}
		t.top=n-1;
		i=0;
		while(i<=n)//出栈模拟 
		{
			if(s.data[s.top]==t.data[t.top]&&s.top!=-1)//如果两个栈元素相同,说明压栈压到了该弹出的元素,弹出 
			{
				Pop(&s);
				Pop(&t);
			}
			else if(s.top<m-1&&i<n)//栈未满的情况下按顺序压栈 
			{
				i++;
				Push(&s,i);
			}
			else
			break;
		}
		if(s.top==-1&&t.top==-1)//s栈能按t栈顺序,两个栈全部Pop空 
		cout<<"YES"<<endl;
		else
		cout<<"NO"<<endl;
	}
	return 0;
} 
//注意栈T是反向存储的 
//S栈按照从1开始的顺序压栈,反复的比较S和T的栈顶
//如果栈顶元素相同,就弹出,否则继续对S进行压栈(在栈未满的情况下)
//如果这个输入的pop序列是合法的,那么就能顺利的弹出两个栈的所有元素
//即两个栈的栈顶指针都指向-1; 
//本题利用STL写会更简单,此处是为了熟悉stack结构 
总结:本题主要考察了栈操作的模拟,还有一种解法是,合法的栈混洗要求任意从头开始的操作序列中,PUSH次数都严格的不小于POP

猜你喜欢

转载自blog.csdn.net/qq_33657357/article/details/80407741