十分简单的实现题目,用Stack可以很快的解决这个问题。
每一次检查几个不同的情况:
1. top堆是空的,这时候只要检查branch堆的堆顶是不是下一个要下放到lake的数,如果不是那么这个case就是N。
2. top堆不为空,这时候要检查top堆的堆顶是不是下一个数,如果不是就检查branch堆顶。 如果不符合以上两种情况,只要把top堆堆顶推到branch堆里面就好了。
import java.io.*; import java.util.*; public class CCC14S3{ static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } public static void main(String[] args) { FastReader sc = new FastReader(); int N = sc.nextInt(); for(int jj = 0 ; jj < N ;jj++){ Stack <Integer> top = new Stack(); Stack <Integer> branch = new Stack<>(); int a = sc.nextInt(); for(int i =0 ; i < a ; i ++){ top.add(sc.nextInt()); } int goal = 1; boolean ans = true; while(true){ if(top.empty()){ if(branch.empty())break; if(branch.peek() != goal){ ans = false; break; }else{ branch.pop(); goal ++; } }else{ if(top.peek() == goal){ top.pop(); goal ++; }else if(!branch.empty() && branch.peek() == goal){ branch.pop(); goal ++; }else{ branch.push(top.pop()); } } } System.out.println(ans?"Y":"N"); } } }