Cod sursa(job #2650348)

Utilizator alexradu04Radu Alexandru alexradu04 Data 18 septembrie 2020 14:45:24
Problema Secv Scor 40
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 1.08 kb
#include <cstdio>
#include <map>

using namespace std;
int v[5005];
int fr[5005];
int prevPos[5005];
int lastPos[5005];
int dp[5005];
map<int, int> c;

int main() {
    freopen("secv.in","r",stdin);
    freopen("secv.out","w",stdout);
    int n;
    scanf("%d", &n);
    for (int i = 1; i <= n; ++i) {
        scanf("%d", &v[i]);
    }
    for (int i = 1; i <= n; ++i) {
        if (fr[v[i]] == 0) {
            c[v[i]]++;
            fr[v[1]] = 1;
        }
    }
    int pos = 0;
    for (auto it : c) {
        ++pos;
        fr[it.first] = pos;
    }
    for (int i = 1; i <= n; ++i) {
        v[i] = fr[v[i]];
        if (v[i] == 1) {
            prevPos[i] = i;
        } else
            prevPos[i] = lastPos[v[i] - 1];
        lastPos[v[i]] = i;
    }
    int minn = 1e9;
    for (int i = 1; i <= n; ++i) {
        if (prevPos[i]) {
            dp[i] = dp[prevPos[i]] + i - prevPos[i];
        } else
            dp[i] = 1e9;
        if (v[i] == c.size())
            minn = min(minn, dp[i]);
    }
    if (minn == 1e9) {
        printf("-1");
    }
    printf("%d", minn + 1);
    return 0;
}