Cod sursa(job #764731)

Utilizator informatician28Andrei Dinu informatician28 Data 6 iulie 2012 00:33:19
Problema Secv Scor 60
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.5 kb
#include <fstream>
#include <set>
#define DIM 5001
#define INF 0x3f3f3f3f

using namespace std;

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

int N, V[DIM], father[DIM], best[DIM], lmax, Sol;
set< int > S;

void Read()
{
    in >> N;
    for (int i = 1; i <= N; i++)
    {
        in >> V[i];
        S.insert(V[i]);
    }
}

void Solve()
{
    int i, j;

    for (i = 1; i <= N; i++)
    {
        father[i] = i;
        best[i] = 1;
    }
    for (i = 1; i <= N; i++)
    {
        for (j = i-1; j >= 1; j--)
        {
            if (V[j] < V[i])
            {
                if (best[j] + 1 == best[i])
                {
                    father[i] = max(father[i], father[j]);
                }
                else if (best[j] + 1 > best[i])
                {
                    best[i] = best[j] + 1;
                    father[i] = father[j];
                }
            }
        }
        if (best[i] > lmax)
        {
            lmax = best[i];
        }
    }
}
int length (int pos)
{
    if (best[pos] == 1)
    {
        return 1;
    }
    return length(father[pos]) + pos - father[pos];
}
int main()
{
    Read();
    Solve();
    if (lmax != S.size())
    {
        out << "-1";
    }
    else
    {
        Sol = INF;
        for (int i = 1; i <= N; i++)
        {
            if (best[i] == lmax)
            {
                Sol = min(Sol, length(i));
            }
        }
    }
    out << Sol;
    return 0;
}