02-线性结构4 Pop Sequence



Given a stack which can keep  MM numbers at most. Push  NN numbers in the order of 1, 2, 3, ...,  NN 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  MM is 5 and  NN 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): MM (the maximum capacity of the stack), NN (the length of push sequence), and KK (the number of pop sequences to be checked). Then KK lines follow, each contains a pop sequence of NN 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
刚开始一直没想明白,后来参考了别人的代码才明白应该如何做

//CheckStack类
package popsequence;

import java.util.Stack;

public class CheckStack {
	static boolean checkStack(int a[],int b,int c){//b=n,c=m
		Stack<Integer> stack =new Stack<Integer>();
		int idx=0;
		int num=1;
		int length=b;
		int stackSize=c;
		stack.push(0);
		while(idx!=length){
			while(stack.peek()<a[idx]&&idx!=length&&(stack.size()<=stackSize)){
				stack.push(num++);
			}
			if(stack.peek()==a[idx]){
				stack.pop();
				idx++;
			}
			else{
				
				return false;
			}
		}
		return true;
	}
}
main

package popsequence;
import java.util.*;
///判断是否为可能的出栈顺序

public class Main {
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner in=new Scanner(System.in);
		//int M,N,K;
		int M=in.nextInt();
		int N=in.nextInt();
		int K=in.nextInt();
		int[][] data =new int[K][N];
		for(int i=0;i<K;i++){
			for(int j=0;j<N;j++){
				data[i][j]=in.nextInt();
			}
		}
		boolean flag;
		for(int i=0;i<K;i++){
			flag=CheckStack.checkStack(data[i],N,M);
			if(flag){
				System.out.println("Yes");
			}
			else{
				System.out.println("No");
			}
		}
	}
}
总体思路为:

先push进去一个0,从而使得比较可以进行。

如果栈顶元素比第一个出栈元素要小,则入栈。

如果栈满,则比较出栈元素和栈顶元素,如果不等,错误;相等则出栈,重复这一步骤;

若在栈满之前相等,则pop,和下一个出栈元素比较,重复以上步骤。

顺便PTA的Java代码怎么传类文件啊?不是很清楚,都不知道怎么提交。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值