题目
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
思路
某个元素a[i]后面,比a[i]小的值构成的连续序列需满足:
- 递减
- 长度不超过栈高
从第一个元素开始,不断找上述连续序列,若其中有不符合要求的,则输出“NO”;若将序列正常遍历结束,则输出“YES”。
柳神用了模拟栈的方法,更直观一点。
代码
#include <iostream>
#include <vector>
using namespace std;
int main(){
int m, n, k;
cin >> m >> n >> k;
vector<int> a(n);
for (int i=0; i<k; i++){
for (int j=0; j<n; j++){
cin >> a[j];
}
bool ret = true;
//l到r是降序序列
int l = 0;
while (l<n){
//找比a[l]小的元素构成的序列
int r = l+1;
while (r<n && a[r]<a[l]){
//若非递减,则不合法
if (a[r]>a[r-1]){
ret = false;
break;
}
r++;
}
//若长度大于栈高,则不合法
if (r-l > m){
ret = false;
break;
}
l = r;
}
if (ret){
cout << "YES" << endl;
}
else{
cout << "NO" << endl;
}
}
return 0;
}
本文探讨了如何判断一个给定的数列是否能通过一个有限容量的栈进行压栈和弹栈操作得到。输入包括栈的最大容量、压栈序列长度及待验证的弹栈序列数量。文章提供了详细的解题思路与C++代码实现。
473

被折叠的 条评论
为什么被折叠?



