ACM ICPC World Finals 2017
Shortest judge solution: 771 bytes. Shortest team solution (during contest): 686 bytes.
Python solutions by the judges: only Pypy (but for no good reason, should be feasible with CPython as well)
This is a fairly straight-forward dynamic programming problem. Let C (i, j) be the minimum squared error cost of posterizing pixels with intensities r1, . . . , ri using j colors. The quantity we are looking for is then C (d, k).
We can formulate the following recurrence for C:
C (i, j) = min0 ≤ i < i0 C (i0, j − 1) + F (i0 + 1, i),
where we define F (a, b) to be the minimum cost of posterizing pixels with intensities ra, . . . , rb using a single color. Assuming for the moment that we have computed the function F, it is a standard exercise in dynamic programming to turn this recurrence into an algorithm for computing C (i, j) in time O(i2 j).
Computing F (a, b) can be done in a few different ways. Note that
F (a, b) = minx ∈ Z ∑i = ab pi (x − ri)2.
This is just a quadratic function in x, so the best x can be found by basic calculus (or some form of ternary search for those so inclined).
There are just d2 different possible inputs to F and the answer for all these can be precomputed to be used when computing C. The bounds were actually small enough that it was even possible to get away with recomputing F (a, b) every time it was needed, at least if the implementation had good constant factors.