Cod sursa(job #2305678)

Utilizator mihailrazMihail Turcan mihailraz Data 20 decembrie 2018 20:21:02
Problema Subsir crescator maximal Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.11 kb
/// O(n*logn)
#include <fstream>
#include <stack>
#define NMAX 100000

using namespace std;
ifstream fi("scmax.in");
ofstream fo("scmax.out");
int n, dim, rightmost;
int X[NMAX+5], last[NMAX+5], PRE[NMAX+5];
stack <int> S;

int bSearch(int x)
{
    int lo=1, hi=dim, mid, res=0;
    while(lo<=hi)
    {
        mid=lo+(hi-lo)/2;
        if(X[last[mid]]<x)
        {
            res=mid;
            lo=mid+1;
        }
        else
            hi=mid-1;
    }
    return res;
}

void afisare(int pos)
{
    while(pos)
    {
        S.push(X[pos]);
        pos=PRE[pos];
    }
    while(!S.empty())
    {
        fo<<S.top()<<" ";
        S.pop();
    }
}

int main()
{
    fi>>n;
    for(int i=1; i<=n; i++)
        fi>>X[i];

    last[1]=1;
    dim=1;
    for(int i=2; i<=n; i++)
    {
        rightmost=bSearch(X[i]);
        if(rightmost==dim)
            last[++dim]=i;
        else
            last[rightmost+1]=i;
        PRE[last[rightmost+1]]=last[rightmost];
    }

    fo<<dim<<"\n";
    afisare(last[dim]);
    fi.close();
    fo.close();
    return 0;
}