02-线性结构4 Pop Sequence

来源:互联网 发布:touchslide.js 编辑:程序博客网 时间:2024/06/05 11:15


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 51 2 3 4 5 6 73 2 1 7 5 6 47 6 5 4 3 2 15 6 4 3 7 2 11 7 6 5 4 3 2

Sample Output:

YESNONOYESNO
刚开始一直没想明白,后来参考了别人的代码才明白应该如何做

//CheckStack类package popsequence;import java.util.Stack;public class CheckStack {static boolean checkStack(int a[],int b,int c){//b=n,c=mStack<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 stubScanner 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