Cod sursa(job #617468)

Utilizator a_h1926Heidelbacher Andrei a_h1926 Data 14 octombrie 2011 21:52:56
Problema Secv Scor 80
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.71 kb
#include <iostream>
#include <cstdio>
#include <set>

#define NMax 5005

using namespace std;

int N, DP[NMax], V[NMax], LMax, F[NMax], S=NMax;
set <int> Sequence;

inline int Min (int a, int b)
{
    if (a<b)
    {
        return a;
    }
    return b;
}

bool Valid ()
{
    int iMax=N;
    for (int i=N; i>0; --i)
    {
        if (DP[i]==LMax)
        {
            iMax=i;
            break;
        }
    }
    for (int i=iMax; i>0; i=F[i])
    {
        Sequence.insert (V[i]);
    }
    for (int i=1; i<=N; ++i)
    {
        if (Sequence.find (V[i])==Sequence.end ())
        {
            return false;
        }
    }
    return true;
}

void Read ()
{
    freopen ("secv.in", "r", stdin);
    scanf ("%d", &N);
    for (int i=1; i<=N; ++i)
    {
        scanf ("%d", &V[i]);
    }
}

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

void LIS ()
{
    for (int i=1; i<=N; ++i)
    {
        DP[i]=1;
        for (int j=i-1; j>0; --j)
        {
            if (V[j]<V[i])
            {
                if (DP[j]+1>DP[i])
                {
                    DP[i]=DP[j]+1;
                    F[i]=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 (!Valid ())
    {
        S=-1;
        Print ();
        return 0;
    }
    for (int i=N; i>0; --i)
    {
        if (DP[i]==LMax)
        {
            S=Min (S, Length (i));
        }
    }
    Print ();
    return 0;
}