Cod sursa(job #875586)

Utilizator BeilandArnoldArnold Beiland BeilandArnold Data 10 februarie 2013 14:22:24
Problema Subsir crescator maximal Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 1.66 kb
#include <fstream>
#include <vector>

int main(){
    std::ifstream fin("scmax.in");
    std::ofstream fout("scmax.out");

    unsigned N; fin>>N;                   //reading input
    std::vector<unsigned> a(N);
    for(unsigned i=0;i<N;++i) fin>>a[i];
     /*
        unsigned N=5; unsigned a[5]={24,12,15,15,19};
    //*/
    unsigned Lmax, where;                      //lenghth of the LIS
    std::vector<unsigned> tati(N);       /* index of the parent for each element in the LIS and not only
                                            N means end of sequence */
    std::vector<unsigned> MinIndL(N+1);    /* MinIndL[i] is the index of the smallest value in a[] such that
                                         there is an inc subseq of length i anding on that element. */
     /*
    unsigned tati[5], MinIndL[6];
    // */

    MinIndL[0]=0;
    Lmax=1; where=0; tati[0]=N; MinIndL[1]=0;      //set everything up for a[0];
    for(unsigned i=1;i<N;++i){
        //binary search for the biggest j<=L such that MinIndL[j]<a[i] else set j to 0;
        unsigned hi=Lmax, lo=0, j=0;
        while(hi>lo){
            j=lo+(hi-lo+1)/2;
            if(a[MinIndL[j]]>=a[i]){ if(j==0) hi=0; else hi=j-1;        j=0; }
            else lo=j;
        }

        if(j==0) tati[i]=N; else tati[i]=MinIndL[j];
        if(j==Lmax){
            Lmax++; where=i;
            MinIndL[Lmax]=i;
        }
        else if(a[i]<a[MinIndL[j+1]]) MinIndL[j+1]=i;
    }

    //use MinIndL as temp storage:
    unsigned c=0;
    for(;where!=N;where=tati[where]) MinIndL[c++]=a[where];
    fout<<Lmax<<'\n';
    while(c--) fout<<MinIndL[c]<<' ';
    fout<<'\n';
}