Given a stack which can keep numbers at most. Push numbers in the order of 1, 2, 3, …, 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 is 5 and 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): (the maximum capacity of the stack), (the length of push sequence), and (the number of pop sequences to be checked). Then lines follow, each contains a pop sequence of 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 2Sample Output:
YES
NO
NO
YES
NO
分析
- the first line contains 3 numbers (all no more than 1000)
三个不超过1000的数 -
(the maximum capacity of the stack)
堆栈的容量 -
(the length of push sequence)
放入的序列长度 -
(the number of pop sequences to be checked)
需要被检验的序列的数量
随机弹栈,如何判断序列是弹出的序列?
按照最初始的序列顺序,依次:
创建一个栈对象,随意放一个初始序列不包含的数(如0,-1,-2…)到栈中(避免后续判断时,存在空栈抛出异常)
遍历 结果序列:
1. 如果 当前元素>栈顶元素 且 栈容量未饱和,将初始序列的元素入栈;直到 栈容量饱和或者 栈顶元素 >= 当前元素
2. 此时判断 栈顶元素 是否和 当前元素相等,相等则符合弹栈的规律,继续判断后续元素; 否则就是虚假序列
import java.util.Scanner;
import java.util.Stack;
public class Main {
public static boolean check(int[] arr, int m, int n){
Stack<Integer> stack = new Stack<>();
int stackSize = m + 1;
int num = 1;//原始序列的元素
stack.push(0);
for(int i = 0; i < n; i++){//遍历序列
//当栈未满 且 栈顶元素比 序列的当前元素小,继续入栈
while(stack.size() < stackSize && arr[i] > stack.peek()) {
stack.push(num);
num++;
}
if(arr[i] == stack.peek()){//当栈顶元素为序列当前元素时,出栈
stack.pop();
}else{
return false;
}
}
return true;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int m = in.nextInt();//堆栈的容量
int n = in.nextInt();//序列的长度
int k = in.nextInt();//序列的数量
int[][] arr = new int[k][n];
boolean[] result = new boolean[k];
for(int i = 0; i < k; i++){
for(int j = 0; j < n; j++){
arr[i][j] = in.nextInt();
}
result[i] = check(arr[i], m, n);
}
in.close();
for(int i = 0; i < result.length; i++){
if(result[i]){
System.out.println("YES");
}else{
System.out.println("NO");
}
}
}
}