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.
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
刚开始一直没想明白,后来参考了别人的代码才明白应该如何做
//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代码怎么传类文件啊?不是很清楚,都不知道怎么提交。