您的位置:首页 > 产品设计 > UI/UE

PAT A 1051. Pop Sequence (25)

2014-05-19 12:53 288 查看
题目

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


判断一个序列是否可以成为1~n的数压入后的弹出情况。

记录已经出现过的最大的数stack_max(即为已经压入到的数),堆栈中的元素数量,上一次弹出的数。

1、出现一个超过已经出现过的最大的数stack_max的数mm,意味着要压入stack_max+1~mm,判断容量问题,刷新数据,继续。

2、出现一个小于上次弹出的数,弹出,刷新数据,继续。

3、其他,错误,跳出。

这里的空间要求相当宽裕,实际可以用一个堆栈来模拟,判断下堆栈大小、将要压入的数、栈顶的数是否与序列中的下一个数匹配即可。

代码:

#include <iostream>
using namespace std;

const int MAX=0x37777777;
bool Stack_judge(int m,int n,int data[1001]);	//判断是否符合要求

int main()
{
int m,n,k;	//输入数据
int data[1001];		//单次的随机排列数据
cin>>m>>n>>k;

int i,j;
for(i=0;i<k;i++)	//输入并判断
{
for(j=0;j<n;j++)
scanf("%d",&data[j]);
if(Stack_judge(m,n,data))
printf("YES\n");
else
printf("NO\n");
}

return 0;
}

bool Stack_judge(int m,int n,int data[1001])
{
int stack_max=0;	//当前堆栈中出现过的最大数字
int stack_num=0;	//当前堆栈中的数字数量(不包括当前弹出的那个)
int last_pop=MAX;	//上次弹出的数字
int i;
for(i=0;i<n;i++)
{
if(data[i]>stack_max)	//比之前最大数大,即要弹出比之前最大更大的数,需要压入数字
{
stack_num+=data[i]-stack_max-1;	//考虑容量是否够
if(stack_num>=m)
return false;
stack_max=data[i];
last_pop=data[i];
}
else if(data[i]<last_pop)	//比之前最大数大但比上一个弹出的小,即继续弹出
{
last_pop=data[i];
stack_num--;
}
else	//比之前最大数大但比上一个弹出的大,不符合要求
return false;
}
return true;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: