Cod sursa(job #1848012)

Utilizator MoodyFaresFares Mohamad MoodyFares Data 15 ianuarie 2017 12:50:18
Problema Secv Scor 100
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.29 kb
#include <cstdio>
#include <queue>
#include <algorithm>
#include <climits>
#include <vector>

using namespace std;
const int MAX_N = 5000;

vector <int> v;
vector <int> norm;
queue <int> q;

bool f[MAX_N + 5];

int main () {
  freopen ("secv.in", "r", stdin);
  freopen ("secv.out", "w", stdout);

  int N;
  int my_max = 0;
  scanf ("%d", &N);
  for (int i = 0; i < N; ++i) {
    int x;
    scanf ("%d", &x);
    v.push_back (x);
    norm.push_back (x);
  }
  sort(norm.begin(), norm.end());
  norm.erase (unique (norm.begin(), norm.end()), norm.end());

  int i = 0;
  for (auto &it : v) {
    it = lower_bound (norm.begin(), norm.end(), it) - norm.begin();
    if (it > my_max)
      my_max = it;
    if (it == 0)
      q.push (i);
    ++i;
  }

  int my_min = INT_MAX;
  while (!q.empty()) {
    int poz = q.front();
    q.pop();
    f[0] = true;
    int last = 0;
    for (i = poz; i <= N; ++i) {
      if (v[i] == last + 1) {
        f[v[i]] = true;
        last = v[i];
      }
      if (f[my_max] == true)
        break;
    }
    if (f[my_max])
      my_min = min (i - poz + 1, my_min);
    for (i = 0; i <= my_max; ++i)
      f[i] = false;
  }

  if (my_min != INT_MAX)
    printf ("%d\n", my_min);
  else
    printf ("-1\n");
  return 0;
}