题目描述
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
题目分析
判断合法出栈队列(原理上)
大头兵可以管住后面的小的,按照递减顺序排列
对于大于栈大小M的兵,必须排在栈内,也就是小于M的地方
判断合法出栈序列(模拟)(怎么能够忘记可以利用计算机的算力去模拟呢?)
根据出出栈序列进行模拟,如果下一个出栈的元素x不在栈顶,那么就入栈
如果下一个出栈的元素x在栈顶,那就直接出栈
成立条件是 出栈序列模拟完成,不成立条件是出栈序列不能模拟完成或者栈内元素个数超出栈的大小
收获
这属于模拟题,思路要扩展一下,这可以用模拟栈的入栈出栈来解决
如果栈为空的话,是不能直接取s.top()的,应当在栈为空的时候,去push一个元素,来防止直接取top出错
注意在scanf的循环中使用break,一定要确保读完后面的内容,才可以进行下一行的scanf()
清空栈不能用clear
// 清空栈
while(s.size()!=0)
{
s.pop();
}
代码
#include <iostream>
#include <vector>
#include <string>
#include <map>
#include <algorithm>
#include <unordered_map>
#include <cstring>
#include <unordered_set>
#include <sstream>
#include<stack>
using namespace std;
int main() {
stack<int> s;
int M,N,K;
int x;
scanf("%d %d %d",&M,&N,&K);
int m=1;
bool flag = true;
for(int i=0;i<K;i++)
{
//
for(int j=0;j<N;j++) //看看能不能遍历完一个模拟输出
{
scanf("%d",&x);//这是即将输出的元素
// 根据元素来决定是入栈还是出栈
if(s.empty())
{
s.push(m++);
}
while(s.top()!=x && s.size()<M)
{
s.push(m++);
}
// 说明要么相等,要么超出了栈的大小
if(s.top()==x)
{
s.pop();
continue;
}
else
{
if(s.size()>=M)
{
flag = false;
//如果直接break的话,后面的字符就读不进去了
}
}
}
flag?printf("YES\n"):printf("NO\n");
// 清空栈
while(s.size()!=0)
{
s.pop();
}
m=1;
flag = true;
}
return 0;
}