PTA栈

PTA
7-3 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.
栈的开始

在这里插入代码片
#include<iostream>
#include<string>
#include<map>
#include<set>
#include<cstdio>
#include<stack>
using namespace std;
int main(){
	int m,n,k;
	scanf("%d%d%d",&m,&n,&k);
	int a[2000];
	int i;
	stack<int>st;
	while(k--){
		int cur=1;//数组的下标 
		int flag=1;//输出的标志 
		while(!st.empty()){
			st.pop();
		}
		for(i=1;i<=n;i++){
			scanf("%d",&a[i]);
		}
		for(int i=1;i<=n;i++){ // 入栈操作 
			st.push(i);
			if(st.size()>m){
				flag=0;
				break;
			}
			while(!st.empty() && st.top()==a[cur]){ //配对 
				st.pop();
				cur++;
			}
		}
		if(st.empty() && flag==1)printf("YES\n");//注意加上栈为空的条件,需要把栈的元素都剔除 
		else printf("NO\n");
	}
    return 0;
}

发布了3 篇原创文章 · 获赞 0 · 访问量 31
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 游动-白 设计师: 上身试试

分享到微信朋友圈

×

扫一扫,手机浏览