浙大数据结构的编程题——02-线性结构4 Pop Sequence
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
思路
输入输出不再多说.<Check>
函数是去尝试模拟入栈操作的.<v>
中是要去模拟的情况,
所以当<stack>
顶部小于要模拟的值时,要先将小的值入栈,当然此时如果堆栈已满,则不能入栈
.当栈顶等于要模拟的值时,出栈.若没有相等的情况,则无法模拟成功,返回<false>
.若完整模拟整个
<v>
,则返回<true>
.
My Code
#include <iostream>
#include <string>
#include <vector>
#include <list>
#include <map>
#include <algorithm>
#include <iterator>
#include <math.h>
#include <stack>
using namespace std;
int Check(vector<int> &v,int &M)
{
int N = v.size();
int i = 0;
int num = 1;
int cap = M + 1;
stack<int> sta;
sta.push(0);
while (i < N)
{
while (v[i] > sta.top() && sta.size() < cap)
sta.push(num++);
if (v[i++] == sta.top())
sta.pop();
else
return 0;
}
return 1;
}
int main(){
//begin: end:
ios::sync_with_stdio(false);
//Given a stack which can keep M numbers at most. Push N numbers in the order of 1, 2, 3, ..., N and pop randomly.
int M, N, K;
cin >> M >> N >> K;
vector<int> line(N);
for (int i = 0; i < K; i++) {
for (int j = 0; j < N; j++) {
cin >> line[j];
}
if (Check(line,M))
printf("YES\n");
else
printf("NO\n");
//line.clear();
}
return 0;
}