Cod sursa(job #2742200)

Utilizator DragosC1Dragos DragosC1 Data 20 aprilie 2021 14:10:01
Problema Subsir crescator maximal Scor 70
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.42 kb
#include <fstream>
#include <algorithm>
using namespace std;

int n, a[100001], poz[100001], shorten[100001], t[100001], dp[100001], fq[100001], longest;

int query(int x) {
    int Max = 0;
    while (x) {
        if (dp[fq[x]] > dp[Max])
            Max = fq[x];
        x -= (x ^ (x - 1) & x);
    }
    return Max;
}

void update(int x, int ind) {
    while (x <= n) {
        if (dp[ind] > dp[fq[x]])
            fq[x] = ind;
        x += (x ^ (x - 1) & x);
    }
}

int main() {
    int i, l;

    freopen("scmax.in", "r", stdin);
    scanf("%d", &n);
    for (i = 1; i <= n; i++)
        scanf("%d", &a[i]);
    for (i = 1; i <= n; i++)
        poz[i] = shorten[i] = a[i];

    sort(shorten + 1, shorten + n + 1);
    l = 1;
    for (i = 2; i <= n; i++)
        if (shorten[i] != shorten[i - 1])
            shorten[++l] = shorten[i];

    for (i = 1; i <= n; i++)
        poz[i] = lower_bound(shorten + 1, shorten + l + 1, poz[i]) - shorten;
    
    for (i = 1; i <= n; i++) {
        t[i] = query(poz[i] - 1);
        dp[i] = dp[t[i]] + 1;
        update(poz[i], i);
    }

    for (i = 1; i <= n; i++)
        if (dp[i] > dp[longest])
            longest = i;

    l = 0;
    for (i = longest; i; i = t[i]) 
        shorten[++l] = a[i];

    freopen("scmax.out", "w", stdout);
    printf("%d\n", dp[longest]);
    for (i = l; i; i--)
        printf("%d ", shorten[i]);

    return 0;
}