Cod sursa(job #3183422)

Utilizator davidenko22Stancu David-Andrei davidenko22 Data 11 decembrie 2023 20:02:41
Problema Subsir crescator maximal Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.02 kb
#include <fstream>
#include <vector>
#include <algorithm>

using namespace std;

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

int interogare(vector <int> &aib, int poz)
{
    int l_max = 0;
    while (poz != 0)
    {
        l_max = max(l_max, aib[poz]);
        int p2 = (poz & (-poz));
        poz -= p2;
    }
    return l_max;
}

void actualizare(vector <int> &aib, int poz, int val)
{
    int n = (int)aib.size() - 1;
    while (poz <= n)
    {
        aib[poz] = max(aib[poz], val);
        int p2 = (poz & (-poz));
        poz += p2;
    }
}

void refac_subsir(vector <int> &v, vector <int> &lung, int poz, int lg, int val_max)
{
    if (lg == 0)
    {
        return;
    }
    int val_c = v[poz];
    if (val_c < val_max && lung[poz] == lg)
    {
        refac_subsir(v, lung, poz - 1, lg - 1, val_c);
        out << val_c << " ";
    }
    else
    {
        refac_subsir(v, lung, poz - 1, lg, val_max);
    }
}

int main()
{
    int n;
    in >> n;
    vector < pair<int, int>> v_ini_perechi(n);
    vector <int> v_norm(n), v_ini(n);
    for (int i = 0; i < n; i++)
    {
        in >> v_ini[i];
        v_ini_perechi[i].first = v_ini[i];
        v_ini_perechi[i].second = i;
    }
    sort(v_ini_perechi.begin(), v_ini_perechi.end());
    int val = 1;
    v_norm[v_ini_perechi[0].second] = val;
    for (int i = 1; i < n; i++)
    {
        if (v_ini_perechi[i].first > v_ini_perechi[i-1].first)
        {
            val++;
        }
        v_norm[v_ini_perechi[i].second] = val;
    }
    vector <int> aib(val + 1, 0), lung(n);
    int poz_max = 0;
    for (int i = 0; i < n; i++)
    {
        int lg = interogare(aib, v_norm[i] - 1);
        lung[i] = lg + 1;
        actualizare(aib, v_norm[i], lg + 1);
        if (lung[i] > lung[poz_max])
        {
            poz_max = i;
        }
    }
    out << lung[poz_max] << "\n";
    refac_subsir(v_ini, lung, poz_max, lung[poz_max], v_ini[poz_max] + 1);
    in.close();
    out.close();
    return 0;
}