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
<mark>谷歌翻译:</mark>
02-线性结构4 Pop Sequence(25分)
给定一个最多可以保留M个数字的堆栈。 按1,2,3,…,N的顺序按N个数字并随机弹出。 您应该判断给定的数字序列是否是堆栈的可能弹出序列。 例如,如果M是5且N是7,我们可以从堆栈中获得1,2,3,4,5,6,7,但不能获得3,2,1,7,5,6,4。
输入规格:
每个输入文件包含一个测试用例。 对于每种情况,第一行包含3个数字(全部不超过1000):M(堆栈的最大容量),N(推送序列的长度)和K(要检查的弹出序列的数量)。 然后是K行,每行包含一个N个数字的弹出序列。 一行中的所有数字都用空格分隔。
输出规格:
对于每个弹出序列,如果它确实是堆栈的可能弹出序列,则在一行中打印“是”,否则打印在“是”。
样本输入:
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
样本输出:
YES
NO
NO
YES
NO
<mark>题解:就是给了你1到n的入栈元素,问出栈的元素顺序是否合法。</mark>
其实就是用程序实现了从出栈倒推回入栈的过程。也就是pop和push的过程,就是一个完美的模拟。
举一个例子:5 6 4 3 7 2 1
要想出栈5,则必须将5之前(包括5)的元素都压入栈中,再判断一下当前栈顶是否为5,是的话就将其pop掉,继续查找6,当前栈顶为4,不是6,就继续压入6,栈顶等于当前值则pop掉,若能找到最后元素1时,说明当前顺序合法。
若找某个元素时,压入栈中的元素已经到达了n,栈顶还不是当前元素,说明找不到该值,则说明该出栈顺序不合法。或者当前栈为空时也不合法。有一个找不到就已经不合法了,可以直接break了。
<mark>注意事项:</mark>
1、压入栈的元素为1~n,所以压到n时就不能再往里面压了。
2、栈的容量为m,所以栈里面的元素个数始终不能超过m,即
if(cur>n||s.size()>=m)
break;
4、要将栈定义到while里面,每组数据都是一个新栈,若定义到外面,最好做一个清空栈的操作,因为上一组数据可能会影响到下一组数据的操作。若上一组栈还没有空,下一组元素很明显就多了。
#include <iostream>
#include <cstdio>
#include <string>
#include <vector>
#include <queue>
#include <stack>
#include <algorithm>
using namespace std;
typedef long long ll;
#define maxn 1000005
#define mod 7654321
int arr[maxn];
int main()
{
//栈的容量 n为1~n的元素 k组数据
int m,n,k;
cin>>m>>n>>k;
//其实就是一个模拟出栈与入栈的过程
while(k--)
{
int f=1,cur=1;
//一定要定义到while里面,因为每次都是一个新栈,
//防止上一次的操作对当前的影响
stack<int> s;
for(int i=0;i<n;i++)
cin>>arr[i];
for(int i=0;i<n;i++)
{
//s.empty()只有第一次时会进入
//判断当前栈顶是否为需要出栈的元素
while(s.empty()||s.top()!=arr[i])
{
if(cur>n||s.size()>=m)//
break;
//不是的话就将cur压入栈中,直到当前栈顶为该元素
//或者压入的cur已经大于了最大值n,或者栈中元素个数大于等于m时退出
s.push(cur++);
}
//栈顶不是当前元素或者栈为空时则说明找不到当前值说明该顺序不合法,退出
if(s.top()!=arr[i]||s.empty())
{
f=0;break;
}
else
s.pop();//找到当前值则将其pop掉,继续下一次查找。
}
//输出
if(f)
cout<<"YES"<<endl;
else
cout<<"NO"<<endl;
}
return 0;
}