Cod sursa(job #2892116)

Utilizator avtobusAvtobus avtobus Data 20 aprilie 2022 20:41:53
Problema Subsir crescator maximal Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.77 kb
#include <algorithm>
#include <stdio.h>
#include <bits/stdc++.h>

using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
typedef vector<int> vi;
typedef vector<ll> vll;

const int NEUTRAL_VALUE{0}; // TODO: update this
int N;
// AIB for max operation
vector<int> aib_val, aib_ind;
// set tree[pos] = val;
void set_val(int pos, int val, int i) {
  for(int x = pos; x <= N; x += x & -x) {
    if (aib_val[x] < val) {
      aib_val[x] = val;
      aib_ind[x] = i;
    }
  }
}
// get maximum on [1,pos]
pii get_max(int pos) {
  int res = NEUTRAL_VALUE, ind = -1;
  for(int x = pos; x; x -= x & -x) {
    if (res < aib_val[x]) {
      res = aib_val[x];
      ind = aib_ind[x];
    }
  }
  return {res, ind};
}

int main(void) {
  freopen("scmax.in", "r", stdin);
  freopen("scmax.out", "w", stdout);
  std::ios_base::sync_with_stdio(false);
  std::cin.tie(nullptr);
  cin >> N;
  vector<int> A(N);
  for(int i = 0; i < N; i++) {
    cin >> A[i];
  }
  vector<int> index(A.begin(), A.end());
  sort(index.begin(), index.end());
  index.erase(unique(index.begin(), index.end()), index.end());

  for(auto &x: A) {
    x = lower_bound(index.begin(), index.end(), x) - index.begin();
  }
  aib_val.resize(N+1, NEUTRAL_VALUE);
  aib_ind.resize(N+1, -1);
  vector<int> dp(N), par(N, -1);
  for(int i = 0; i < N; i++) {
    auto tmp = get_max(A[i]);
    dp[i] = tmp.first + 1;
    par[i] = tmp.second;
    set_val(A[i]+1, dp[i], i);
  }

  int best = 0, el = -1;
  for(int i = 0; i < N; ++i) {
    if (best < dp[i]) {
      best = dp[i];
      el = i;
    }
  }
  cout << best << "\n";
  vector<int> res;
  for(; el != -1; el = par[el]) {
    res.push_back(index[A[el]]);
  }
  reverse(res.begin(), res.end());
  for(auto x: res) { cout << x << " "; } cout << "\n";
  return 0;
}