Pagini recente » Cod sursa (job #2251937) | Cod sursa (job #1721983) | Cod sursa (job #2731546) | Cod sursa (job #2486582) | Cod sursa (job #2776338)
#include <fstream>
#include <set>
using namespace std;
ifstream cin("secv.in");
ofstream cout("secv.out");
int v[5005], urm[5005], l[5005];
set <int> s;
void simul(int &st, int &dr, int poz)
{
st = poz;
while (poz)
{
dr = poz;
poz = urm[poz];
}
}
int main()
{
int n, poz, lmax = 0, first, last, i, j;
first = last = -1;
cin >> n;
if (n == 0)
{
cout << -1;
return 0;
}
for (i = 1; i <= n; i++)
{
cin >> v[i];
s.insert(v[i]);
}
urm[n] = 0;
l[n] = 1;
for (i = n - 1; i >= 0; i--)
{
urm[i] = 0;
l[i] = 1;
for (j = i + 1; j <= n; j++)
if (v[i] < v[j])
if (l[i] < l[j] + 1)
{
l[i] = l[j] + 1;
urm[i] = j;
}
}
for (i = 1; i <= n; i++)
if (lmax < l[i])
{
lmax = l[i];
if (lmax == s.size())
{
int st, dr;
simul(st, dr, i);
if (first == -1)
{
first = st;
last = dr;
}
else if (last - first > dr - st)
{
first = st;
last = dr;
}
}
}
else if (lmax == s.size() and l[i] == lmax)
{
int st, dr;
simul(st, dr, i);
if (first == -1)
{
first = st;
last = dr;
}
else if (last - first > dr - st)
{
first = st;
last = dr;
}
}
if (lmax != s.size())
{
cout << -1;
return 0;
}
cout << last - first + 1;
}