Cod sursa(job #3215848)

Utilizator AlexInfoIordachioaiei Alex AlexInfo Data 15 martie 2024 13:35:59
Problema Subsir crescator maximal Scor 90
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.46 kb
#include <bits/stdc++.h>

using namespace std;

ifstream in("scmax.in");
ofstream out("scmax.out");

#define pii pair<int, int>
#define pb push_back
#define fi first
#define se second

const int NMAX = 1e5 + 30;
const int INF = 0x3f3f3f3f;

int n, a[NMAX], p[NMAX], d[NMAX];
vector<int> ans;

void read()
{
    in >> n;
    for (int i = 1; i <= n; i++)
        in >> a[i];
}

void solve()
{
    int k = 1;
    d[1] = a[1]; // d[k] -> last element in a increasing subsequence of k length
    p[1] = 1;    // p[i] = a[i]'s position in d
    for (int i = 2; i <= n; i++)
        if (a[i] > d[k])
            d[++k] = a[i], p[i] = k;
        else
        {
            int le = 1, ri = k, poz=k+1;
            while (le <= ri)
            {
                int m = (le + ri) / 2;
                if (d[m]>a[i])
                    poz = m, ri = m-1;  
                else
                    le = m+1; //pana gasim cel mai mic element din d > a[i]
            }
            d[poz] = a[i];
            if (poz==k+1) k++;
            p[i] = poz;
        }
    
    out<<k<<'\n';

    int j = n;
    for (int i = k; i >= 1; i--)
    {
        while (p[j] != i)
            j--;
        ans.pb(a[j]);
    }


    for (auto it = ans.end() - 1; it >= ans.begin(); it--)
        out << *it << ' ';
}

int main()
{
    cin.tie(0);
    cout.tie(0);
    ios_base::sync_with_stdio(false);

    read();
    solve();

    return 0;
}