1051 Pop Sequence (25 分)题解

1051 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

这题其实不难,对时间和空间的复杂度要求也不高,但是这个题确实能看个人水平。这题考察的重点是对过程的抽象能力,说到底,编程就是对实际事务的抽象,而编程能力很多情况下都和抽象能力是挂钩的,通过这道题,我也能感觉到自己在过程的抽象能力方面是存在不足的,最后还是借鉴了其他博主的思路,才完成了这道题,那我就简单讲一下这道题的思路吧。

我认为,这道题是存在两个思路的,一个是模拟题目给的序列,进行入栈和出栈,如果能完全模拟这个过程且不超出规定容量则为“YES”,否则为“NO”,最后我也是采取了这个思路。这个过程首先是把出栈序列先存储在一个数组里,然后设一个变量index来标记数组下标,从1到N的顺序对栈S进行进栈操作,如果进栈后超过规定容量,则break,说明这个过程无法实现,若没有超容量,则进行下一个操作,那就是比对数组V[index]和栈顶元素是否相等,若相等则出栈,index++,如此循环判断,直到栈为空或不相等。若循环结束后index没有等于N,则说明这个过程无法模拟,因此这个过程是不可能的。

还有一个思路是我最初的思路,就是根据出栈的序列,得到进栈的顺序,如果这个进栈的顺序与题目要求的一致为1到N,且在这个过程中栈的大小没有超过规定大小,则为“YES”,否则为“NO”。但是在后来遇到一些问题,比如如何判断是否超出容量?因为我并不是模拟栈的过程,而是对出栈结果的逆推,得到进栈顺序,因此不好判断是否超出容量。有可能是我对这个思路把握得不好,如果这个思路有什么好的想法的话欢迎留言。

代码如下:

#include <iostream>
#include<stack>
#include<vector>
#include<string>

using namespace std;

int main()
{
	int M, N, K;
	cin >> M >> N >> K;
	stack<int> s;
	vector<int> numberArr(N);
	for (int i = 0; i < N; i++)
	{
		numberArr[i] = i + 1;
	}
	vector<string> FinalResult;
	for (int i = 0; i < K; i++)
	{
		int flag = 0;
		vector<int> subArr;
		for (int j = 0; j < N; j++)
		{
			int temp;
			cin >> temp;
			subArr.push_back(temp);
		}
		int index = 0;
		for(int j=1;j<=N;j++)
		{
			s.push(j);
			if (s.size() > M)
			{
				//flag++;
				break;
			}
			while (!s.empty() && s.top() == subArr[index])
			{
				s.pop();
				index++;
			}
			if (index == N)
			{
				flag = 1;
			}
		}
		if (flag > 0)
		{
			FinalResult.push_back("YES");
		}
		else if (flag == 0)
		{
			FinalResult.push_back("NO");
		}
		while (!s.empty())
		{
			s.pop();
		}
	}
	for (int i = 0; i < FinalResult.size(); i++)
	{
		if (i != FinalResult.size() - 1)
		{
			cout << FinalResult[i] << endl;
		}
		else
		{
			cout << FinalResult[i];
		}
		
	}
	system("pause");
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_38279908/article/details/88040949