题目
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
解答
首先根据题意把所有的数都读取下来,逐行进行判断。
将1至N-1连续的数放到一个临时数组中,对输入行的每个数字逐一判断,如果该数字减去先前放进stack的最大数仍大于stack的capacity,则中断循环;如果该数字大于先前放进stack的最大数,则push差值进stack,并pop首位;如果该数字等于stack的栈顶,则pop;如果都不满足,则break;
最后根据是否完成遍历以及stack中是否还残留元素 来判断YES or NO
import java.io.*;
import java.util.Stack;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str = br.readLine();
String[] a = str.split(" ");
int capacity = Integer.parseInt(a[0]);
int length = Integer.parseInt(a[1]);
int num = Integer.parseInt(a[2]);
int[] sequence = new int[length];
int[] initial = new int[length];
for (int i = 0; i < length; i++) {
initial[i] = i + 1;
}
int[][] arr = new int[num][length];
for (int i = 0; i < num; i++) {
str = br.readLine();
a = str.split(" ");
for (int j = 0; j < length; j++) {
arr[i][j] = Integer.parseInt(a[j]);
}
}
br.close();
//根据序列个数决定循环次数
for (int i = 0; i < num; i++) {
Stack stack = new Stack();
int size = 0; //栈中的个数
sequence = arr[i];
int j = 0;
int contrast = 0; //用来和序列中遇到的下一个数比较的值,如果序列中大的话,则push与contrast的差值,小的话则pop
for (j = 0; j < length; j++) {
if (sequence[j] - contrast > capacity - size) {
break;
} else if (contrast < sequence[j]) {
for (int z = contrast; z < sequence[j]; z++) {
stack.push(initial[z]);
size++;
}
contrast = sequence[j];
stack.pop();
size--;
} else if (sequence[j] == (int)stack.peek()) {
stack.pop();
size--;
} else {
break;
}
}
if (j == length && stack.isEmpty()) {
System.out.print("YES");
} else {
System.out.print("NO");
}
if (i != num - 1) {
System.out.println();
}
}
}
}