Cod sursa(job #3266373)

Utilizator lucky1992Ion Ion lucky1992 Data 7 ianuarie 2025 21:15:57
Problema Subsir crescator maximal Scor 100
Compilator java Status done
Runda Arhiva educationala Marime 1.64 kb
import java.io.*;
import java.util.StringTokenizer;

public class Main {

  public static void print(PrintStream ps, int[] a, int[] pred, int last) {
    if (pred[last] != 0) print(ps, a, pred, pred[last]);
    ps.print(a[last] + " ");
  }

  public static int binarySearch(int x, int low, int high, int[] a, int[] L) {
    int right = high;
    while (low <= high) {
      int mid = (low + high) >>> 1;

      if (a[L[mid]] < x && x <= a[L[mid+1]]) {
        return mid;
      } else if (a[L[mid+1]] < x) {
        low = mid + 1;
      } else {
        high = mid - 1;
      }
    }

    return right;
  }

  public static void main(String[] args) throws IOException {
    try (BufferedReader reader = new BufferedReader(new FileReader("scmax.in"));
         PrintStream ps = new PrintStream(new FileOutputStream("scmax.out"), true)) {

      StringTokenizer st = new StringTokenizer(reader.readLine());

      int N = Integer.parseInt(st.nextToken());
      int[] a = new int[N+1];

      st = new StringTokenizer(reader.readLine());

      for (int i = 1; i <= N; i++) {
        a[i] = Integer.parseInt(st.nextToken());
      }

      int[] dp = new int[N+1];
      int[] pred = new int[N+1];
      int[] L = new int[N+1];

      a[0] = Integer.MIN_VALUE; // dummy sentinel

      int max = 1;
      int last = 1;
      dp[1] = 1;

      L[1] = 1;

      for (int i = 2; i <= N; i++) {
        int poz = binarySearch(a[i], 0, max, a, L);
        dp[i] = poz + 1;
        pred[i] = L[poz];
        L[poz + 1] = i;

        if (max < poz + 1) {
          max = poz + 1;
          last = i;
        }
      }

      ps.println(max);
      print(ps, a, pred, last);
    }
  }
}