1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
| #include <iostream>
#define INF 2000000000
using namespace std;
int n, ans = INF, os[9][2] = { {0,0}, {0, 1}, {0, -1}, {1, -1}, {1, 0}, {1, 1}, {-1, -1}, {-1, 0}, {-1, 1} };
int diff, nums[100010];
int min(int a, int b) {
return a < b ? a : b;
}
int abs(int a) {
return a < 0 ? -a : a;
}
int dfs(int d, int prev) {
if (d == n - 1)
return 0;
int res = INF;
for (int j = -1; j <= 1; j++) {
nums[d + 1] += j;
if ((nums[d + 1] - nums[d]) == diff)
res = min(res, dfs(d + 1, j) + abs(j));
nums[d + 1] -= j;
}
return res;
}
int main() {
cin >> n;
for (int i = 0; i < n; i++)
cin >> nums[i];
if (n <= 2) {
cout << 0;
return 0;
}
for (int i = 0; i < 9; i++) {
nums[0] += os[i][0]; nums[1] += os[i][1];
diff = nums[1] - nums[0];
ans = min(ans, dfs(1, nums[1]) + abs(os[i][0]) + abs(os[i][1]));
nums[0] -= os[i][0]; nums[1] -= os[i][1];
}
if (ans >= INF - 200000)
cout << -1;
else
cout << ans;
}
|