Cod sursa(job #2367341)

Utilizator AplayLazar Laurentiu Aplay Data 5 martie 2019 10:15:50
Problema Subsir crescator maximal Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.86 kb
#include <cstdio>

#define LENGTH_MAX 100000

using namespace std;

typedef struct {
    int value, position;
} HELPER;

int N, n[LENGTH_MAX], len[LENGTH_MAX], prev[LENGTH_MAX], helpLength = 0, maxLength = 0, maxIndex;
HELPER help[LENGTH_MAX];

int getPrev(int value) {
    if (0 == helpLength) return -1;
    int start = 0, end = helpLength - 1;
    while (start < end) {
        int middle = start + (end - start) / 2 + 1;
        if (help[middle].value < value) {
            start = middle;
        } else {
            end = middle - 1;
        }
    }
    return end;
}

void printSolution(int start) {
    if (-1 != prev[start]) {
        printSolution(prev[start]);
    }
    printf("%d ", n[start]);
}

int main() {
    freopen("scmax.in", "r", stdin);
    freopen("scmax.out", "w", stdout);

    scanf("%d", &N);
    for (int it = 0; it < N; ++it) {
        scanf("%d", &n[it]);
    }

    for (int it = 0; it < N; ++it) {
        //for (int it = 0; it < helpLength; ++it) printf("%d ", help[it].value);
        //printf("\n");
        int previous = getPrev(n[it]);
        //printf("%d\n", previous);
        if (n[it] <= help[previous].value) --previous;
        if (-1 == previous) {
            len[it] = 1;
            prev[it] = -1;
        } else if (help[previous].value < n[it]) {
            len[it] = 1 + len[help[previous].position];
            prev[it] = help[previous].position;
        }

        if (0 <= previous + 1 && ((previous + 1 < helpLength && n[it] < help[previous + 1].value) || helpLength == previous + 1)) {
                help[previous + 1].value = n[it];
                help[previous + 1].position = it;
                if (helpLength == previous + 1) ++helpLength;
        }

        if (maxLength < len[it]) {
            maxLength = len[it];
            maxIndex = it;
        }
    }

    printf("%d\n", maxLength);
    printSolution(maxIndex);

    return 0;
}