Problem — 2153D - 18 - Not Alone
My solution — 343107994
Explanation of the solution ---------------------------
A nice array consists only of groups of equal consecutive elements (each group size ≥ 2). We can cover the array with blocks of length 2 or 3: - Cost to make 2 adjacent equal = |x − y| - Cost to make 3 adjacent equal = sum of distances to their median
Let dp[i] = minimum cost to make the first i elements nice (linear case): dp[i] = min( dp[i-2] + cost2(i-2), dp[i-3] + cost3(i-3) ) where cost2(i)=|a[i]-a[i+1]| and cost3(i) = total distance to median of 3 numbers. Because the array is circular, the last elements may connect to the first. We only need to test three rotations — starts at 0, n-1, and n-2 — since segments are length ≤ 3. Take the minimum DP result among them.
There is an efficient way of making this shift by making use of modulo as pasted below
vector starts; starts.push_back(0); if (n-1 != 0) starts.push_back(n-1); if (n-2 >= 0) starts.push_back(n-2);
for (int s : starts) {
vector<ll> b(n);
for (int i = 0; i < n; ++i) b[i] = a[(s + i) % n];
ans = min(ans, solve_linear(b));
}See the submission attached for the whole code








Auto comment: topic has been updated by ekagra444 (previous revision, new revision, compare).
Auto comment: topic has been updated by ekagra444 (previous revision, new revision, compare).
Sir, clearly you used AI if you can't even explain why we only need blocks of sizes 2 and 3 and not 6 or 7.
I articulated the solution's blog with the help of ai, just wanted to post this solution because it was a simpler approach to the problem and i saw few editorials taking a difficult approach to the problem.
For your question of using block of sizes 2 and 3, i thought it was trivial, but here is my thought process — i used 2 and 3 block sizes as all the other big block sizes can be made from these and as for the purpose of satisfying the required condition of equal values. eg- as you asked why not blocks of size 6, it can be broken into 3 blocks of size 2. If you think why can't we think block of size 3 as two blocks having one element in common, my answer would be — it would be difficult to manage dp state for that.
Hope you understood why to take blocks of size specifically of sizes 2 and 3.