Cod sursa(job #2334208)

Utilizator PetrescuAlexandru Petrescu Petrescu Data 2 februarie 2019 12:31:43
Problema Secv Scor 30
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 1.44 kb
#include <algorithm>
#include <fstream>
#include <iostream>
#define MAX 5001

using namespace std;
int v[MAX], copie[MAX], T[MAX], R[MAX];

int main()
{
    int n, i, contor, st, dr, mij, gasit, length;

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

    fin >> n;

    for(i = 1; i <= n; i++)
    {
        fin >> v[i];
        copie[i] = v[i];
    }
    sort(v + 1, v + 1 + n);

    contor = 1;
    for(i = 2; i <= n; i++)if(v[i] != v[i - 1])contor++;

    T[1] = 1;
    length = 1;

    for(i = 2; i <= n; i++)
    {
        st = 1;
        dr = length;

        gasit = -1;

        while(st <= dr)
        {
            mij = (st + dr) / 2;
            if(copie[i] < copie[T[mij]])
            {
                gasit = mij;
                dr = mij - 1;
            }
            else st = mij + 1;
        }

        if(gasit == -1 && copie[i] > copie[T[length]])
        {
            R[i] = T[length];
            length++;
            T[length] = i;
        }
        else if(copie[T[gasit - 1]] < copie[i])
        {
            R[i] = T[gasit - 1];
            T[gasit] = i;
        }
    }

    if(length != contor)fout << -1;
    else
    {
        i = T[length];

        dr = T[length];

        while(R[i] != 0)
        {
            i = R[i];
        }

        st = i;

        fout << dr - st + 1;
    }

    fin.close();
    fout.close();

    return 0;
}