1051 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
这题蛮有意思的,数据结构考试就经常考这类,没想到这次需要算法实现
仔细想了想还是直接模拟实现最简单了
大概过程如下:
如果第一个要求输出元素是5我们就需要把12345都压到栈里面,再pop出来5,第二个要求输出的元素要么是没入栈的元素并且这个元素入栈后栈的大小还需要不超过给定的一个数字否则错误,要么是栈里面的元素,栈里面的元素必须是栈顶元素,非栈顶元素就是错误的
#include <iostream>
#include <algorithm>
using namespace std;
#include <unordered_map>
#include <queue>
#include <stack>
int main()
{
//int sn[100][100]={0};
int maxStack,num,inNum;
cin>>maxStack>>num>>inNum;
for(int p=0; p<inNum; p++)//一共需要判断inNum次
{
int sn[num];//用数列sn记录需要输出的元素
for(int i=0; i<num; i++)
{
cin>>sn[i];
}
//生成输入队列 1 到7,因为栈的输入顺序是1-7,用队列更方便点得到需要输入的元素
queue<int> que;
for(int i=1; i<=num; i++)
que.push(i);
//判断数组,用来判断哪些元素在栈里面,1即为在栈内
int inStack[num+1]= {0};
int sign=1;
//判断是否符合了规则
stack<int> sta;
for(int i=0; i<num&&sign; i++)
//这个sign就是如果已经有元素位置不对了,就没必要再判断后面的元素了
{
if(sta.size()==0||inStack[sn[i]]==0)
//栈为空或者栈里面没有我们需要输出的元素
{
while(que.front()!=sn[i])//一直输出元素,知道得到了我们需要压栈的元素
//比如7 我们就需要压入1 2 3 4 5 6
{
sta.push(que.front());
//判断是否越界
if(sta.size()>maxStack)
{
sign=0;
break;
}
//标记栈中存在了压入的元素
inStack[que.front()]=1;
que.pop();
}
if(sign)//这是把7 再压入栈,为了方便判断是否超过栈的最大容量了
{
sta.push(que.front());
inStack[que.front()]=1;
que.pop();
//判断是否越界
if(sta.size()>maxStack)
{
sign=0;
break;
}
sta.pop();
}
}
else if(sn[i]==sta.top())//元素在栈顶
{
sta.pop();
continue;
}
else//元素不在栈顶,肯定就是不行的
{
sign=0;
break;
}
}
if(sign==1)
cout<<"YES";
else
cout<<"NO";
cout<<endl;
}
return 0;
}