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
这道题开始我怎么都不明白是什么意思,思考了很久发现其实就是一个栈的先进后出后进先出的问题,由于是randomly pop 所以刚push的数据随时可能pop,但一定是按照1,2,3,…,n这样的顺序push,本题就是让你判断pop出来元素顺序是否符合栈
比如1 2 3 4 5 6 7 可以是push1 pop1,push2,pop2…,push7 ,pop7,同时要注意容量M,当容量满时一定会pop栈顶元素,同时空栈不能push,如5 6 4 3 7 2 1(刚开始怎么也想不通为什么是YES,后来发现容量就是5)所以先push 1 2 3 4 5,栈容量满了所以pop 5 ,栈未满,再push 6 pop6,再pop 4 pop 3,push 7 pop7,没有可以push的就把剩余的都pop,pop2,pop1
#include <iostream>
#include <vector>
#include <stack>
using namespace std;
int m,n,k;
bool check(vector<int> &v)
{
int i = 0,cap = m + 1,num = 1;
stack<int>s;
s.push(0);/*先push 0 是为了方便判断栈顶元素与pop出的元素是否符合*/
while(i < n)
{
while(v[i] > s.top()/*如果pop出的元素大于栈顶元素证明栈正在不停的push*/ && s.size() < cap/*但不能超过容量cap*/)
{
s.push(num++);/*按照1,2,3,...,n的顺序push*/
}
if(v[i++] == s.top())/*如果停止push就证明要pop。如果这时栈顶元素等于pop出的元素就符合栈*/
{
s.pop();
}
else/*否则就不符合*/
{
return false;
}
}
return true;
}
int main()
{
vector<int>v;
cin >> m >> n >> k;
for(int i = 0 ; i < k ; i++)
{
for(int j = 0 ; j < n ; j++)
{
int q;
cin >> q;
v.push_back(q);
}
if(check(v))/*检查*/
{
cout << "YES" << endl;
}
else
{
cout << "NO" << endl;
}
v.clear();/*不要忘了多组数据要清空vector*/
}
return 0;
}