02-线性结构4 Pop Sequence (25 分)中国大学MOOC-陈越、何钦铭-数据结构-2018秋

版权声明:欢迎转载,但转载时请注明原文地址 https://blog.csdn.net/weixin_42110638/article/details/84203048

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, ..., Nand 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

作者: 陈越

单位: 浙江大学

时间限制: 400 ms

内存限制: 64 MB

代码长度限制: 16 KB

题意:这个题就是给出一个序列问是否有一个合理的进栈顺序,如果存在合理的进栈序列则这个序列是YES,否则是NO

题解:开一个栈,因为每次都是1到n的合理序列,所以先把1压进去好写一点,然后每一步判断是不是和给出这个序列的第一个元素一样,如果一样序列加一,同时弹栈。否则按顺序继续压栈。当栈大小大于给出的m,break就好了。(注意每一步要清空栈)。

#include<bits/stdc++.h>
using namespace std;
 
int a[10010];
int main()
{
	int m,n,k;
	cin >> m >> n >> k;
	stack<int> sk;	
	while(k--){
		bool flag = 1;
		for(int i=1;i<=n;i++)	cin >> a[i];
		int w = 1;
		sk.push(w);
		for(int i=1;i<=n;){
			if(!sk.empty() &&(sk.top()==a[i])) sk.pop(),i++;
			else w++,sk.push(w);
			if(sk.size()>m){
				flag = 0;
				break;
			}
		}
		if(!sk.empty())	flag = 0;
		if(flag)	cout <<"YES\n";
		else cout <<"NO\n";	
		while( !sk.empty() )  sk.pop();
	}	
	return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_42110638/article/details/84203048