Pop Sequence (25)

版权声明:本文章由BlackCarDriver原创,欢迎评论和转载 https://blog.csdn.net/BlackCarDriver/article/details/89364669

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.

输入描述:
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.

输出描述:
For each pop sequence, print in one line “YES” if it is indeed a possible pop sequence of the stack, or “NO” if not.

输入例子:
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

输出例子:
YES
NO
NO
YES
NO


大意
若按照顺序给你1~n这n个数,允许你用一个容量为m的栈作中转站,问你能否输出特定的整数序列。

分析
最直接的思路就是用一个栈来模拟这个过程,能不放栈则直接输出,否则压入栈。
若栈的高度超出了限制,则不能实现。

My Code

#include<iostream>
#include<stdio.h>
#include<stack>
using namespace std;
typedef stack<int> istack;
const int maxn = 1009;
int output[maxn];
istack temp;
//clear all element in temp
void clear(){
	while (!temp.empty()) temp.pop();
}
int main(){
	int n, m, q;
	scanf("%d%d%d", &n, &m, &q);
	while (q--){
		//get input data
		for (int i = 0; i < m; i++) scanf("%d", &output[i]);
		//simulate each input
		bool have = true;	//can find or not
		int input = 1;		//the value shold output next
		clear();
		for (int i = 0; i< m; i++){
			//directly pop from input
			if (output[i] == input){
				input++;
				continue;
			}
			//check if can pop from the stack
			if (!temp.empty() && temp.top() == output[i]){	//you should check if it is empty before use pop method 
				temp.pop();
				continue;
			}
			//push into stack if it can
			while (output[i] != input && temp.size()<n-1 && input <= m){	
				temp.push(input++);
			}
			if (output[i] != input){
				have = false;
				break;
			}
			else if (input<m){
				input++;
			}

		}
		if (have) cout << "YES" << endl;
		else cout << "NO" << endl;
	}
	return 0;
}

备忘录
因为没有在草稿纸上先写好思路,做这道题时将input 和ouput 搞混乱了,浪费了
不少时间,下次一定要有一个清晰的思路再开打。另外读取栈顶的时候因为试过未判断
栈是否为空就读取了,实在不该犯的错误。

猜你喜欢

转载自blog.csdn.net/BlackCarDriver/article/details/89364669