Cod sursa(job #3141092)

Utilizator verde.cristian2005Verde Flaviu-Cristian verde.cristian2005 Data 12 iulie 2023 11:34:08
Problema Subsir crescator maximal Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.59 kb
#include <bits/stdc++.h>
using namespace std;

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

int aib[100001], n;
int v[100001], vec[100001], cnt;
int lungmax[100001];

int lsb(int x)
{
    return x & -x;
}

void update(int poz, int val)
{
    for(; poz <= n; poz += lsb(poz))
        aib[poz] = max(aib[poz], val);
}

long long query(int poz)
{
    int max1 = 0;
    for(; poz > 0; poz -= lsb(poz))
        max1 = max(max1, aib[poz]);
    return max1;
}

int cautbin(int val)
{
    int r = 0, pas = 1 << 16;
    while(pas)
    {
        if(r + pas <= cnt && vec[r + pas] <= val)
            r += pas;
        pas /= 2;
    }
    return r;
}

int afis[100001];

///aib[i] = cel mai lung subsir care se termina intr-o valoare din intervalul (i - lsb(i) + 1, i)

int main()
{
    in >> n;
    for(int i = 1; i <= n; i++)
    {
        in >> v[i];
        vec[i] = v[i];
    }
    sort(vec + 1, vec + n + 1);
    for(int i = 1; i <= n; i++)
        if(vec[i] != vec[i - 1])
            vec[++cnt] = vec[i];
    for(int i = 1; i <= n; i++)
        v[i] = cautbin(v[i]);
    int max1 = 0;
    for(int i = 1; i <= n; i++)
    {
        lungmax[i] = 1 + query(v[i] - 1);
        max1 = max(max1, lungmax[i]);
        update(v[i], lungmax[i]);
    }
    out << max1 << '\n';
    int cnt = max1, last = 2e9;
    for(int i = n; i >= 1; i--)
        if(lungmax[i] == cnt && v[i] < last)
        {
            last = v[i];
            afis[cnt--] = vec[v[i]];
        }
    for(int i = 1; i <= max1; i++)
        out << afis[i] << " ";
    return 0;
}