Cod sursa(job #2871143)

Utilizator cristi_macoveiMacovei Cristian cristi_macovei Data 12 martie 2022 21:43:54
Problema Subsir crescator maximal Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.58 kb
#define d(x) std::cout << x << std::endl
#define dm(msg, x) std::cout << msg << x << std::endl

#define all(a) a.begin(), a.end()
#define range(a, l, r) a.begin() + l, a.begin() + r
#define aall(a, n) a + 1, a + 1 + n
#define arange(a, l, r) a + l, a + r
	
#define maxself(a, b) a = std::max(a, b);
#define minself(a, b) a = std::min(a, b);

#define inout(f) std::ifstream in((f) + (std::string) ".in");std::ofstream out((f) + (std::string) ".out")

#include <iostream>
#include <fstream>
#include <limits>

const int NMAX = 1e5;

int n;
int a[1 + NMAX];

int orderedIndices[1 + NMAX];
int prev[1 + NMAX];

int bsUpperBound(int i) {
  int left = 1, right = n, mid, ans = n;

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

    if (a[orderedIndices[mid]] >= a[i]) {
      right = mid - 1;
      ans = mid;
    }
    else 
      left = mid + 1;
  }

  return ans;
}

void printPath(std::ostream& out, int index) {
  if (prev[index] != 0)
    printPath(out, prev[index]);

  out << a[index] << ' ';
}

int main() {
  inout("scmax");

  in >> n;
  for (int i = 1; i <= n; ++i)
    in >> a[i];
  a[0] = std::numeric_limits<int>::max();

  int ans = -1;
  for (int i = 1; i <= n; ++i) {
    // for each element, find the first one that's greater than it
    int bestPos = bsUpperBound(i);

    // replace that element with the current one
    orderedIndices[bestPos] = i;
    prev[i] = orderedIndices[bestPos - 1];

    maxself(ans, bestPos);
  }

  out << ans << '\n';

  printPath(out, orderedIndices[ans]);
  out << '\n';

  return 0;
}