Cod sursa(job #651955)

Utilizator a_h1926Heidelbacher Andrei a_h1926 Data 22 decembrie 2011 15:56:19
Problema Secv Scor 100
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.68 kb
#include <fstream>
#include <cstdio>
#include <vector>
#include <algorithm>

#define NMax 5005

using namespace std;

int N, DP[NMax], V[NMax], LMax, F[NMax], S=NMax;
vector <int> Elements;

void Read ()
{
    freopen ("secv.in", "r", stdin);
    //ifstream fin ("secv.in");
    scanf ("%d", &N);
    //fin >> N;
    for (int i=1; i<=N; ++i)
    {
        scanf ("%d", &V[i]);
        //fin >> V[i];
        Elements.push_back (V[i]);
    }
    sort (Elements.begin (), Elements.end ());
    Elements.erase (unique (Elements.begin (), Elements.end ()), Elements.end ());
}

void Print ()
{
    freopen ("secv.out", "w", stdout);
    //ofstream fout ("secv.out");
    printf ("%d\n", S);
    //fout << S << "\n";
}

void LIS ()
{
    for (int i=1; i<=N; ++i)
    {
        F[i]=i;
        DP[i]=1;
        for (int j=i-1; j>0; --j)
        {
            if (V[j]<V[i])
            {
                if (DP[j]+1==DP[i])
                {
                    F[i]=max (F[i], F[j]);
                }
                if (DP[j]+1>DP[i])
                {
                    DP[i]=DP[j]+1;
                    F[i]=F[j];
                }
            }
        }
        if (DP[i]>LMax)
        {
            LMax=DP[i];
        }
    }
}

int Length (int i)
{
    if (DP[i]==1)
    {
        return 1;
    }
    return Length (F[i])+i-F[i];
}

int main()
{
    Read ();
    LIS ();
    if (LMax!=Elements.size ())
    {
        S=-1;
        Print ();
        return 0;
    }
    for (int i=N; i>0; --i)
    {
        if (DP[i]==LMax)
        {
            S=min (S, Length (i));
        }
    }
    Print ();
    return 0;
}