Pop Sequence
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、需要入栈的整数个数n、总共要判断的组数k,整数按照1-n的顺序依次入栈,但出栈时间随机,要求判断每一组序列是否是可能的出栈顺序。
思路
可以直接模拟入栈出栈:将当前将要入栈的整数a与目标序列对应的整数b比较,如果 a == b,说明a入栈后要马上出栈,并将目标序列的比较对象移至下一个整数,,这时要注意判断栈是否已满;如果 a < b,说明a必须先入栈,注意判断栈是否已满;如果 a > b,说明与b相等的整数已经入栈,只要判断栈顶元素是否与b相等即可。
代码实现
#include <cstdio>
#include <stack>
#include <vector>
using namespace std;
bool judge(int m, int n, int k, vector<int> v) // v为目标序列
{
stack<int> s;
int i = 1;
int index = 0; // 当前正在比较的目标序列中整数的下标
while (i <= n) // 依次判断整数1-n
{
if (i == v[index]) // i与目标整数相同
{
if (s.size() == m) // 实际操作为i先入栈再出栈,所以若栈已满则返回false
return false;
index++; // 与下一个整数比较
i++;
}
else if (i < v[index]) // i小于目标整数,需要先入栈
{
if (s.size() == m) // 栈满false
return false;
s.push(i); // i入栈
i++;
}
else if (i > v[index]) // i大于目标整数,说明栈顶元素必须与目标整数相同
{
if (s.top() != v[index]) // 不同则返回false
return false;
s.pop(); // 栈顶元素出栈
index++; // 比较下一个整数
}
}
while (!s.empty()) // n个整数全部入过栈,处理栈中剩余元素
{
if (s.top() != v[index]) // 依次比较每个元素与目标整数是否相同
return false;
s.pop();
index++;
}
return true;
}
int main()
{
int m, n, k;
vector<int> num;
int x;
scanf("%d %d %d", &m, &n, &k);
for (int i = 0; i < k; i++)
{
num.clear();
for (int j = 0; j < n; j++)
{
scanf("%d", &x);
num.push_back(x);
}
if (judge(m, n, k, num))
printf("YES\n");
else
printf("NO\n");
}
return 0;
}