Cod sursa(job #2168702)

Utilizator NicuBaciuNicu Baciu NicuBaciu Data 14 martie 2018 11:59:55
Problema Potrivirea sirurilor Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.25 kb
#include <fstream>
#include <iostream>
#include <stack>
#include <algorithm>

using namespace std;

ifstream fin("scmax.in");
ofstream fout("scmax.out");

int a[100002];
int t[100002];
int r[100002];
int lmax=0;
int temp[100002];
int n;

int main()
{
    fin >> n;

    for(int i=0; i<n; i++)
        fin >> a[i];

    for(int i=0; i<n; i++)
        r[i]=-1;

    for(int i=1; i<n; i++)
    {
        if(a[i]>a[t[lmax]])
        {
            t[lmax+1]=i;
            lmax++;

            r[i]=t[lmax-1];
        }
        else if(a[i]<a[t[0]])
            t[0]=i;
        else if(a[i]!=a[t[lmax]])
        {
            int mid, st=0, dr=lmax+1;

            while(st<dr)
            {
                mid=(st+dr)/2;

                if(a[t[mid]]<a[i])
                    st=mid+1;
                else if(a[t[mid]]>=a[i])
                    dr=mid;
            }

            t[st]=i;
            r[i]=t[st-1];
        }
    }

    fout << lmax+1 << '\n';

    stack <int> s;

    int ind=t[lmax];

    while(r[ind]!=-1)
    {
        s.push(a[ind]);

        ind=r[ind];
    }

    s.push(a[ind]);

    while(!s.empty())
    {
        fout << s.top() << " "; s.pop();
    }

    return 0;
}