堆栈
判断输入的序列是否可以从确定栈中得到
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.
import java.util.*;
class stack{
int Max;
int data[];
int top=-1;
public stack(int M) {
this.Max = M;
data = new int[Max];
}
public void push(int item) {
if(top == Max-1) {
// System.out.println("O");
}
else {
data[++top] = item;
}
}
public int pop() {
if(top == -1) {
return -1;
}
else {
return data[top--];
}
}
}
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int max = in.nextInt();
int num =in.nextInt();
int[] n = new int[num];
int K = in.nextInt();
for(int k = K; k>0; k--) {
int p = 1;
int last=0;
stack s = new stack(max);
for(int i = 0; i<num; i++) {
n[i] = in.nextInt();
}
loop:
{
for(int i = 0; i<num; i++) {
while(p<=n[i]) {
if(s.top == s.Max-1) {
System.out.println("NO");
break loop;
}
s.push(p);
last = p;
p++;
}
if(n[i]==last) {
if(s.pop()==-1) {
System.out.println("NO");
break loop;
}
if(s.top!=-1) {
last = s.data[s.top];
}
}
else {
System.out.println("NO");
break loop;
}
}
System.out.println("YES");
}
}
in.close();
}
}
(竟然一次过!可能方法刚好和题目要考察的一些特殊情况匹配。)