Skip to content

Commit 52f5880

Browse files
committed
Solve problem 978D from codeforces
1 parent acfa2f2 commit 52f5880

File tree

2 files changed

+69
-0
lines changed

2 files changed

+69
-0
lines changed
Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
/*
2+
Idea:
3+
- Brute force.
4+
- The first two elements in any arithmetic progression identify its factor,
5+
so if we try the all possibilities for the first two elements and count
6+
the number of changes each time and take the minimum we will get the
7+
right answer.
8+
*/
9+
10+
#include <bits/stdc++.h>
11+
12+
using namespace std;
13+
14+
int const N = 1e5 + 1;
15+
int n, a[N], b[N];
16+
17+
int check(int chn) {
18+
for(int i = 0; i < n; ++i)
19+
b[i] = a[i];
20+
21+
int fac = b[1] - b[0];
22+
for(int i = 2; i < n; ++i) {
23+
if(b[i] - b[i-1] == fac)
24+
continue;
25+
if((b[i] - 1) - b[i-1] == fac) {
26+
--b[i];
27+
++chn;
28+
continue;
29+
}
30+
if((b[i] + 1) - b[i-1] == fac) {
31+
++b[i];
32+
++chn;
33+
continue;
34+
}
35+
return 1e9;
36+
}
37+
38+
return chn;
39+
}
40+
41+
int main() {
42+
cin >> n;
43+
for(int i = 0; i < n; ++i)
44+
cin >> a[i];
45+
46+
if(n <= 2) {
47+
cout << 0 << endl;
48+
return 0;
49+
}
50+
51+
int res = 1e9;
52+
res = check(0); // .. ..
53+
++a[0], ++a[1];res = min(res, check(2));--a[0], --a[1]; // ++ ++
54+
--a[0], --a[1];res = min(res, check(2));++a[0], ++a[1]; // -- --
55+
++a[0];res = min(res, check(1));--a[0]; // ++ ..
56+
++a[1];res = min(res, check(1));--a[1]; // .. ++
57+
--a[0];res = min(res, check(1));++a[0]; // -- ..
58+
--a[1];res = min(res, check(1));++a[1]; // .. --
59+
--a[0], ++a[1];res = min(res, check(2));++a[0], --a[1]; // -- ++
60+
++a[0], --a[1];res = min(res, check(2));--a[0], ++a[1]; // ++ --
61+
62+
if(res == 1e9)
63+
cout << -1 << endl;
64+
else
65+
cout << res << endl;
66+
67+
return 0;
68+
}

CodeForces/README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -414,6 +414,7 @@
414414
- [978A. Remove Duplicates](http://codeforces.com/contest/978/problem/A)
415415
- [978B. File Name](http://codeforces.com/contest/978/problem/B)
416416
- [978C. Letters](http://codeforces.com/contest/978/problem/C)
417+
- [978D. Almost Arithmetic Progression](http://codeforces.com/contest/978/problem/D)
417418
- [978E. Bus Video System](http://codeforces.com/contest/978/problem/E)
418419
- [978F. Mentors](http://codeforces.com/contest/978/problem/F)
419420
- [979A. Pizza, Pizza, Pizza!!!](http://codeforces.com/contest/979/problem/A)

0 commit comments

Comments
 (0)