Pagini recente » Cod sursa (job #3218937) | Cod sursa (job #1648602) | Cod sursa (job #902994) | Cod sursa (job #1356139) | Cod sursa (job #2193034)
#include <fstream>
#include <algorithm>
using namespace std;
ifstream cin ("secv.in");
ofstream cout ("secv.out");
const int nmax = 5000;
int n, dist;
int lim, lg, pz;
int v[1 + nmax], temp[1 + nmax];
int l[1 + nmax], p[1 + nmax];
int a[1 + nmax];
int search(int x) {
int st = 0, dr = lim, mid;
while(st <= dr) {
mid = (st + dr) / 2;
if(v[l[mid]] < x && x <= v[l[mid + 1]])
return mid;
else if(v[l[mid + 1]] < x)
st = mid + 1;
else
dr = mid - 1;
}
return lim;
}
int main() {
cin >> n;
for(int i = 1; i <= n; i++) {
cin >> v[i];
temp[i] = v[i];
}
sort(temp + 1, temp + n + 1);
dist = 1;
for(int i = 2; i <= n; i++)
if(temp[i - 1] != temp[i])
dist++;
l[1] = lim = 1;
for(int i = 2; i <= n; i++) {
int poz = search(v[i]);
l[poz + 1] = i;
p[i] = l[poz];
lim = max(lim, poz + 1);
if(poz + 1 > lg) {
lg = poz + 1;
a[0] = 0;
a[++a[0]] = i;
} else if(poz + 1 == lg)
a[++a[0]] = i;
}
if(lg != dist)
cout << -1;
else {
int sol = nmax;
for(int i = 1; i <= a[0]; i++) {
pz = a[i];
while(p[pz])
pz = p[pz];
sol = min(sol, a[i] - pz + 1);
}
cout << sol;
}
return 0;
}