给定一个最大容量为 M 的堆栈,将 N 个数字按 1, 2, 3, ..., N 的顺序入栈,允许按任何顺序出栈,则哪些数字序列是不可能得到的?例如给定 M=5、N=7,则我们有可能得到{ 1, 2, 3, 4, 5, 6, 7 },但不可能得到{ 3, 2, 1, 7, 5, 6, 4 }。
输入格式:
输入第一行给出 3 个不超过 1000 的正整数:M(堆栈最大容量)、N(入栈元素个数)、K(待检查的出栈序列个数)。最后 K 行,每行给出 N 个数字的出栈序列。所有同行数字以空格间隔。
输出格式:
对每一行出栈序列,如果其的确是有可能得到的合法序列,就在一行中输出YES
,否则输出NO
。
输入样例:
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
结尾无空行
输出样例:
YES
NO
NO
YES
NO
结尾无空行
import java.util.Scanner;
import java.util.Stack;
public class Main{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt(),m=sc.nextInt(),k=sc.nextInt();//栈的容量,数据个数,待检查的栈的个数
int i,j=0,t=0,A=1;
Stack<Integer> st=new Stack<Integer>();
int num[]=new int[m];
int a[]=new int[m];
for(i=0;i<m;i++)
a[i]=i+1;
while(j<k)
{
for(i=0;i<m;i++)
num[i]=sc.nextInt();
i=0;t=0;
st.clear();
while(t<m)
{
if(st.empty()||st.peek()!=num[t]&&st.size()<n&&i<m) {
st.push(a[i]);
i++;
}
else if(st.peek()==num[t]){
st.pop();
t++;
}
else
{
System.out.println("NO");
break;
}
}
if(t>=m)
System.out.println("YES");
j++;
}
}
}