Cod sursa(job #2217401)

Utilizator andrei.arnautuAndi Arnautu andrei.arnautu Data 30 iunie 2018 12:39:12
Problema Subsir crescator maximal Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.3 kb
/**
  *  Worg
  */
#include <cstdio>
#include <vector>

FILE *fin = freopen("scmax.in", "r", stdin); FILE *fout = freopen("scmax.out", "w", stdout);

const int MAX_N = 1e5 + 5;

/*-------- Data --------*/
int n;
int a[MAX_N];

int size;
int index[MAX_N], prev[MAX_N];
/*-------- --------*/

void ReadInput() {
  scanf("%d", &n);
  for(int i = 1; i <= n; i++) {
    scanf("%d", &a[i]);
  }
}

void ComputeIncreasingSubstring() {
  size = 0;

  for(int i = 1; i <= n; i++) {
    if(a[i] > a[index[size]]) {
      index[++size] = i;
      prev[i] = index[size - 1];
    } else {
      //  Binary search the first position for which a[i] <= a[index[pos]]
      int left = 1, right = size, pos = 0;

      while(left <= right) {
        int mid = (left + right) / 2;

        if(a[i] <= a[index[mid]]) {
          pos = mid; right = mid - 1;
        } else {
          left = mid + 1;
        }
      }

      index[pos] = i;
      prev[i] = index[pos - 1];
    }
  }

  //  Print the size
  printf("%d\n", size);

  //  Print the substring
  std::vector<int > substring;

  int x = index[size];
  while(x != 0) {
    substring.push_back(a[x]);

    x = prev[x];
  }

  for(int i = (int)substring.size() - 1; i >= 0; i--) {
    printf("%d ", substring[i]);
  }
}

int main() {
  ReadInput();

  ComputeIncreasingSubstring();

  return 0;
}