1. 程式人生 > >PAT A1051 Pop Sequence彈出序列 [棧]

PAT A1051 Pop Sequence彈出序列 [棧]

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.

給你一個最多能存放M個數的棧。把N個數以1,2,3,。。。N的順序放入棧,並隨機彈出。你需要判斷一個數字序列是否有可能是棧的彈出序列。比如說,如果M是5,N是7,我們能從棧得到序列1,2,3,4,5,6,7 而不是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.

第一行包含3個數字(每一個都不會大於1000):M N K(需要檢測的彈出序列個數)。然後會有K行,每一行都是包含N個數字的彈出序列。數字之間用空格隔開

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.

對於每一個彈出序列,如果它確實是彈出序列則輸出"YES",否則輸出"NO"。

思路:模擬入棧,讓1-N依次入棧,入棧過程中如果入棧元素恰好等於出棧序列中待出棧元素,就讓棧頂元素出棧。同時把出棧元素指標後移一個。

 

#include<cstdio>
#include<stack>
using namespace std;
const int maxn=1010;

int arr[maxn];//保留題目給定的出棧序列
stack<int> st;//定義棧st,用以存放int型元素

int main(){
	int m,n,T;
	scanf("%d %d %d",&m,&n,&T);

	while(T--){  //迴圈T次
		//1.清空棧 
		while(!st.empty()){
			st.pop();
		}
        //2.接收出棧序列
		for(int i=1;i<=n;i++){
			scanf("%d",&arr[i]);
		}
		int current = 1;//指向出棧序列中的待出棧元素
		bool flag=true;
        //3.模擬入棧出棧
		for(int i=1;i<=n;i++){
			st.push(i);//i入棧
			if(st.size()>m){
				flag=false;
				break;
			} 
			
			while(!st.empty()&&st.top()==arr[current]){
				st.pop();
				current++;
			}
		} 
		//4.輸出
		if(st.empty()==true&&flag==true){
			printf("YES\n");
		}else{
			printf("NO\n");
		}
	}
	return 0;
}