Cod sursa(job #2555801)

Utilizator MarianConstantinMarian Constantin MarianConstantin Data 24 februarie 2020 12:49:48
Problema Secv Scor 80
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 1.13 kb
#include <bits/stdc++.h>

using namespace std;

const int MAXN = 5005;
ifstream fin("secv.in");
ofstream fout("secv.out");

int inp[MAXN], best[MAXN], dp[MAXN], fat[MAXN], k, n;

bool compare(const int &x, const int &y)
{
    return inp[x] < inp[y];
}

void read()
{
    fin >> n;
    for (int i = 1; i <= n; ++i)
        fin >> inp[i];
}

void solve()
{
    for (int i = 1; i <= n; ++i)
        if (inp[i] > inp[dp[k]]) {
            dp[++k] = i;
            best[i] = k;
            fat[i] = dp[k - 1];
        }
        else {
            int ind = lower_bound(dp + 1, dp + k + 1, i, compare) - dp;
            dp[ind] = i;
            fat[i] = dp[ind - 1];
            best[i] = ind;
        }
}

int findPos(int ind)
{
    if (fat[ind] == 0)
        return ind;
    return findPos(fat[ind]);
}

void print()
{
    int mi = MAXN;
    for (int i = 1; i <= n; ++i)
        if (best[i] == k)
            mi = min(mi, i - findPos(i) + 1);
    if (mi == MAXN)
        fout << "-1\n";
    else
        fout << mi << '\n';
}

int main()
{
    read();
    solve();
    print();
    return 0;
}