Cod sursa(job #2047203)

Utilizator whitewolfJon Snow whitewolf Data 24 octombrie 2017 17:20:52
Problema Subsir crescator maximal Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.46 kb
#include <bits/stdc++.h>

using namespace std;

const int nMax = 100005;
int n, a[nMax], lis[nMax], order[nMax], ans[nMax], peek;

void Read() {
    ifstream fin("scmax.in");
    fin >> n;
    for (int i = 1; i <= n; i++)
        fin >> a[i];
    fin.close();
}

/**
*   Caut cea mai din stanga pozitie unde se afla un element mai mare sau egal cu x
*/
int Binary_Search(int k, int x) {
    if (x <= lis[1]) return 1;
    if (x > lis[k]) return k + 1;
    int lf, rg, mid, pos;
    pos = lf = 1; rg = k;
    while (lf <= rg) {
        mid = (lf + rg) / 2;
        if(x <= lis[mid]) {
            pos = mid;
            rg = mid - 1;
        }
        else
            lf = mid + 1;
    }
    return pos;
}

void Solve() {
    int i, x, pos;
    lis[1] = a[1];
    order[1] = peek = 1;
    for (i = 2; i <= n; i++) {
        x = a[i];
        pos = Binary_Search(peek, x);
        if(pos > peek) {
            lis[++peek] = x;
            order[i] = peek;
        }
        else {
            lis[pos] = x;
            order[i] = pos;
        }
    }
}

void Write() {
    ofstream fout("scmax.out");
    fout << peek << "\n";
    int size = peek, i;
    for (i = n; i > 0 && peek > 0; i--)
        if (order[i] == peek)
            ans[peek--] = a[i];
    for (i = 1; i <= size; i++)
        fout << ans[i] << " ";
    fout << "\n";
    fout.close();
}

int main()
{
    Read();
    Solve();
    Write();
    return 0;
}