1051. Pop Sequence (25)

1.这道题是判断出栈队列是否合理。

2.采用了用栈来模拟情况。

3.当目前栈为空,或者栈不为空并且栈顶不等于目标值,并且队列中还有数值可以压入,栈的size小于最大容量,那么就一直循环执行压入操作,把123456789。。。队列中的值依次压入栈,直到跳出循环。

4.跳出循环后,判断栈顶是否等于目标值,不等于的话,这个sequence就是不合理的,如果等于,则把栈顶的值pop掉,再执行步骤3。

1051

时间限制
100 ms
内存限制
65536 kB
代码长度限制
16000 B
判题程序
Standard
作者
CHEN, Yue

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

 
AC代码:

//#include<string>
//#include<stack>
//#include<unordered_set>
//#include <sstream>
//#include "func.h"
//#include <list>
#include <iomanip>
#include<unordered_map>
#include<set>
#include<queue>
#include<map>
#include<vector>
#include <algorithm>
#include<stdio.h>
#include<iostream>
#include<string>
#include<memory.h>
#include<limits.h>
#include<stack>
using namespace std;

int main(void)
{
	int maxCap, maxSequence, querySum;
	cin >> maxCap >> maxSequence >> querySum;
	for (int k = 0; k < querySum; k++)
	{
		int idx = 1;
		stack<int> sta;
		int maxNum = maxCap;//栈里面能够存在的最大的值
		vector<int> sequence(maxSequence);
		for (int i = 0; i < maxSequence; i++)
			scanf("%d", &sequence[i]);
		bool result = true;

		for (int i = 0; i < maxSequence; i++)
		{

			if (sequence[i]>maxNum)
			{//不合理
				result = false;
				break;
			}
			while ((sta.empty() || (!sta.empty() && sta.top() != sequence[i])) && idx <= maxSequence && sta.size() <= maxCap)
			{// 如果栈为空,或者栈不为空但是头部不等于目标值,并且还有值可以压入,队列size小于最大容量
				sta.push(idx++);
			}
			if (sta.top() != sequence[i])
			{//如果经过上面的压入操作后,仍不满足要求,则不合理
				result = false;
				break;
			}
			sta.pop();
			maxNum++;//弹出了一个,可以压入更大的一个值

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

发表评论

电子邮件地址不会被公开。 必填项已用*标注