Pagini recente » Cod sursa (job #2311448) | Cod sursa (job #536024) | Cod sursa (job #3191234) | Cod sursa (job #2637338) | Cod sursa (job #3229910)
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Scanner;
public class secv {
//in: 8
// 2 1 3 2 1 3 4 5
//out: 7
// Singura subsecventa care respecta conditile din enunt este 1 3 2 1 3 4 5
// Acesta subsecventa contine subsirul 1 2 3 4 5.
static final int NMAX = 5015;
static ArrayList<Integer>[] pos = new ArrayList[NMAX];
static int n;
static int[] a = new int[NMAX];
static int[] dp = new int[NMAX];
static HashMap<Integer, Integer> mp = new HashMap<>();
public static void main(String[] args) throws FileNotFoundException {
Scanner fin = new Scanner(new File("secv.in"));
PrintWriter fout = new PrintWriter(new File("secv.out"));
//Scanner fin = new Scanner(System.in);
n = fin.nextInt();
int[] st = new int[n + 1];
for (int i = 1; i <= n; i++) {
st[i] = fin.nextInt();
a[i] = st[i];
mp.put(a[i], i);
}
int cnt = 0;
for (Integer entry : mp.keySet()) {
mp.put(entry, ++cnt);
}
for (int i = 1; i <= n; i++) {
a[i] = mp.get(a[i]);
}
for (int i = 1; i <= n; i++) {
if (pos[a[i]] == null) {
pos[a[i]] = new ArrayList<>();
}
}
for (int i = 1; i <= n; i++) {
if (a[i] == 1) {
pos[1].add(i);
dp[i] = 1;
} else {
if (pos[a[i] - 1].size() > 0) {
int loc = pos[a[i] - 1].get(pos[a[i] - 1].size() - 1);
dp[i] = dp[loc] + (i - loc);
pos[a[i]].add(i);
}
}
}
long ans = Long.MAX_VALUE;
for (int i = 1; i <= n; i++) {
if (a[i] == cnt && dp[i] > 0) {
ans = Math.min(ans, dp[i]);
}
}
fout.println(ans == Long.MAX_VALUE ? -1 : ans);
//System.out.println(ans == Long.MAX_VALUE ? -1 : ans);
fin.close();
}
}