mooc作业题:线性结构: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
解释:
第一行输入栈的大小,再输入序列的长度,输入序列的数量。
接下来分别输入序列。
程序的作用:按顺序输入从1开始的数字,放入到栈中,中间可以选择性的进行出栈操作,检查出栈的数字组成的序列是否和和输入的匹配。
思路:
核心思想是pop出来的数字和cur指向的数字要始终相同。
用一个vector储存输入的序列,索引cur指向第一个元素。然后开始按顺序放数字入栈,只要栈顶的数字小与cur指向的数字,那么久一直入栈,直到栈满或者顶部的数字和数字相等,然后将其pop出来。如果pop和cur相等,那么cur指向下一个,再继续放入,如果pop和cur不相等,直接下结论这个序列是NO。
这个流程保证每次pop出来的数字和cur一样,不然这个序列就是NO。
#include <iostream>
#include <stack>
#include <vector>
using namespace std;
int main()
{
int m, n, k;
cin>>m>>n>>k;
int cap = m+1; //栈的容量,加1是因为会先放一个0进去保证其非空
for(int i = 0; i<k; i++)
{
vector<int> v(n);
stack<int> sta;
sta.push(0);
int cur = 0; //指向序列的每个元素
int num = 1; //入栈的第一个数
for(int j = 0; j < n; j++)
cin>>v[j]; //输入序列
while(cur < n)
{
while(sta.top() < v[cur] && sta.size() < cap)
sta.push(num++);
if(sta.top() == v[cur]) //关键条件,判断两个相等
{
sta.pop();
cur++;
}else {cout<<"NO"<<endl;break;}
}
if(cur == n) //cur移动到了最后一个,说明数字都成功匹配了
cout<<"YES"<<endl;
}
return 0;
}