Cod sursa(job #3170797)

Utilizator amcbnCiobanu Andrei Mihai amcbn Data 18 noiembrie 2023 10:00:54
Problema Subsir crescator maximal Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.89 kb
#include <bits/stdc++.h>
#include <random>
#include <chrono>
using namespace std;
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
const char nl = '\n';
const char sp = ' ';
const int inf = 0x3f3f3f3f;
const long long INF = 1000000000000000000;
const int mod = 1e9 + 7;
const char out[2][4]{ "NO", "YES" };
#define all(a) a.begin(), a.end()
using ll = long long;
ifstream fin("scmax.in");
ofstream fout("scmax.out");

#define variableName(var) #var
#define __debug(var) cout << #var << " = " << var << '\n'
inline int rint(int a, int b) { return uniform_int_distribution<int>(a, b)(rng); }

const int nmax = 1e5;
int n;
int v[nmax + 5]{ 0 };
vector<int> dp{ 0 }; // dp[i] = pozitia minima unde se poate face un subsir crescator de lungime i cu ulitimul element in dp[i]
int p[nmax + 5]{ 0 };
int lenmax = 0;

int find_best(int i) {
    int st = 0, dr = dp.size() - 1, len = 0;
    while (st <= dr) {
        int mid = (st + dr) / 2;
        if (v[dp[mid]] < v[i]) {
            len = mid;
            st = mid + 1;
        }
        else {
            dr = mid - 1;
        }
    }
    return len;
}

int main() {
    ios::sync_with_stdio(0);
    cin.tie(0);
    fin >> n;
    for (int i = 1; i <= n; ++i) {
        fin >> v[i];
    }
    // dp[i] - cel mai mica valoare in care se termina un subsir crescator de lungime i
    // dp[i] este strict crescator
    for (int i = 1; i <= n; ++i) {
        int len = find_best(i);
        p[i] = dp[len];
        if (len + 1 == dp.size()) {
            dp.push_back(i);
        }
        else if (v[dp[len + 1]] > v[i]) {
            dp[len + 1] = i;
        }
    }
    fout << dp.size() - 1 << nl;
    stack<int> pos;
    pos.push(dp.back());
    while (p[pos.top()] > 0) {
        pos.push(p[pos.top()]);
    }
    while (pos.size()) {
        fout << v[pos.top()] << sp;
        pos.pop();
    }
}