Cod sursa(job #1012695)

Utilizator sziliMandici Szilard szili Data 19 octombrie 2013 15:40:37
Problema Subsir crescator maximal Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.84 kb
#include <stdio.h>
#include <stdlib.h>
#include <iostream>

using namespace std;

//the elements
int X[100001];

//on position i, a pointer to the element which is the last one obtaining an increasing subsequence of length i
int m[100001];

//the i'th element's predecessor when appearing in the
int pred[100001];

int solution[100001];
int L = 0;

int binarySearch(int index, int left, int right){

    if (left <= right){
        int middle = (left + right) / 2;

        if (middle == 1 && X[m[1]] >= X[index]){
            return 0;
        }

        if (X[m[middle]] < X[index] && ( middle == L || X[m[middle + 1]] >= X[index])){
            return middle;
        }

        if (X[index] <= X[m[middle]]) {
            return binarySearch(index, left, middle-1);
        }
        else if (X[index] > X[m[middle]]) {
            return binarySearch(index, middle+1, right);
        }

    } else {
        return 0;
    }
}

int maxx(int a, int b){

    if (a>b)
        return a;
    else
        return b;
}


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

    int n;
    scanf("%d", &n);

    for (int i=1; i<=n; i++){
        scanf("%d", &X[i]);
    }

    m[0] = -1;

    for (int i=1; i<=n; i++){
        int j = binarySearch(i, 1, L);

        pred[i] = m[j];

        if (X[m[j + 1]] > X[i] || j == L){
            m[j+1] = i;
        }

        L =maxx(j+1, L);
    }

    //print result
    printf("%d\n", L);

    int currentElementIndex = m[L];
    int solutionIndex = L;

    while (currentElementIndex != -1) {
        solution[solutionIndex--] = X[currentElementIndex];
        currentElementIndex = pred[currentElementIndex];
    }

    for (int i=1; i<=L; i++){
        printf("%d ", solution[i]);
    }


    return 0;
}