Cod sursa(job #3239875)

Utilizator ChopinFLazar Alexandru ChopinF Data 8 august 2024 14:49:12
Problema Subsir crescator maximal Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.15 kb
#include <bits/stdc++.h>
using namespace std;

std::string file = "scmax";
std::ifstream fin(file + ".in");
std::ofstream fout(file + ".out");

int n;
std::vector<int> v, dp, parent, lis_end_index;

int32_t main(int32_t argc, char *argv[]) {
  ios_base::sync_with_stdio(false);
  fin.tie(0);
  fout.tie(0);

  fin >> n;
  v.resize(n + 1);
  dp.resize(n + 1, INT_MAX);
  parent.resize(n + 1, -1);
  lis_end_index.resize(n + 1, -1);

  for (int i = 1; i <= n; ++i)
    fin >> v[i];

  int lis_length = 0;
  int lis_last_index = -1;

  for (int i = 1; i <= n; ++i) {
    int idx = std::lower_bound(dp.begin(), dp.end(), v[i]) - dp.begin();
    dp[idx] = v[i];
    lis_end_index[idx] = i;

    if (idx > 0) {
      parent[i] = lis_end_index[idx - 1];
    }

    if (idx + 1 > lis_length) {
      lis_length = idx + 1;
      lis_last_index = i;
    }
  }

  fout << lis_length << "\n";

  // Reconstruct the LIS by following the parent array
  vector<int> lis;
  for (int i = lis_last_index; i != -1; i = parent[i]) {
    lis.push_back(v[i]);
  }

  reverse(lis.begin(), lis.end());

  for (int i = 0; i < lis.size(); ++i) {
    fout << lis[i] << " ";
  }
  fout << "\n";

  return 0;
}