7-3 Pop Sequence(25 分)
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、主要考察栈(stack)的使用,我直接用了java中stack这个类,当然也可以自己写一个类似的类。
2、一开始我想直接根据M,N,K把所有可能的结果序列都存贮起来,用测试数据逐个对比,后来发现工作量太大,放弃。还是采用给定的输出序列,用人工的想法逐个判断。
3、有一些坑,注意栈的容量K比N小的情况,若出现stack.size( )大于N,直接bool=false,break。
4、犯了一个很傻的错误,ArrayList<int []>存贮的其实是数组的引用,而不会开辟空间存储数组中的具体元素。
5、简单的流程图:
import java.util.ArrayList;
import java.util.Scanner;
import java.util.Stack;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner in = new Scanner(System.in);
int m = in.nextInt();
int n = in.nextInt();
int k = in .nextInt();
ArrayList<int []> al = new ArrayList<>();
int [ ][] a = new int [k][n];
for(int i= 0;i<k;i++) {
for(int j = 0;j<n;j++) {
a[i][j] = in.nextInt();
}
al.add(a[i]);
}
judge(al,k,n,m);
}
private static void judge(ArrayList<int[]> al, int k, int n,int size) {
// TODO Auto-generated method stub
Stack<Integer> st = new Stack<>();
int temp = 0 ;
boolean bool = true;
for(int i = 0;i<k;i++) {
int [] a = al.get(i);
for(int j =0; j < n; j++) {
int m = a[j];
if( m>temp) {
bool=caozuo(st,m,temp,size);
temp=m;
if(bool==false)
break;
}
/
else if(m<temp) {
if(!st.empty()) {
int pop = st.pop();
if(m==pop) {
continue;
}
else {
bool = false;
break;
}
}
else
bool = false;
}
//
}
if(bool == true)
System.out.println("YES");
else
System.out.println("NO");
bool=true;
temp=0;
st.clear();
}
}
private static boolean caozuo(Stack<Integer>st,int m, int temp,int size) {
// TODO Auto-generated method stub
int k = m-temp;
boolean bool = true;
for(int i=1;i<=k;i++) {
st.push(temp+i);
if(st.size()>size) {
bool=false;
break;
}
}
st.pop();
return bool;
}
}