Posterized (Codeforces 980C)
Tags: Greedy, games

Professor Ibrahim has prepared the final homework for his algorithm’s class. He asked his students to implement the Posterization Image Filter.Their algorithm will be tested on an array of integers, where the $$$i$$$-th integer represents the color of the $$$i$$$-th pixel in the image. The image is in black and white, therefore the color of each pixel will be an integer between 0 and 255 (inclusive).To implement the filter, students are required to divide the black and white color range [0, 255] into groups of consecutive colors, and select one color in each group to be the group’s key. In order to preserve image details, the size of a group must not be greater than $$$k$$$, and each color should belong to exactly one group.Finally, the students will replace the color of each pixel in the array with that color’s assigned group key.To better understand the effect, here is an image of a basking turtle where the Posterization Filter was applied with increasing $$$k$$$ to the right.   To make the process of checking the final answer easier, Professor Ibrahim wants students to divide the groups and assign the keys in a way that produces the lexicographically smallest possible array.

Input: The first line of input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq n \leq 10^5$$$, $$$1 \leq k \leq 256$$$), the number of pixels in the image, and the maximum size of a group, respectively.The second line contains $$$n$$$ integers $$$p_1, p_2, \dots, p_n$$$ ($$$0 \leq p_i \leq 255$$$), where $$$p_i$$$ is the color of the $$$i$$$-th pixel.

Output: Print $$$n$$$ space-separated integers; the lexicographically smallest possible array that represents the image after applying the Posterization filter.

Note: One possible way to group colors and assign keys for the first sample:Color $$$2$$$ belongs to the group $$$[0,2]$$$, with group key $$$0$$$.Color $$$14$$$ belongs to the group $$$[12,14]$$$, with group key $$$12$$$.Colors $$$3$$$ and $$$4$$$ belong to group $$$[3, 5]$$$, with group key $$$3$$$.Other groups won't affect the result so they are not listed here.

Sample Inputs:
4 3
2 14 3 4

5 2
0 2 1 255 254

Sample Outputs:
0 12 3 3

0 1 1 254 254

Solution (Python):
[n, k] = map(int, input().strip().split())
pis = list(map(int, input().strip().split()))
import sys
if k == 1:
    print(' '.join(map(str, pis)))
    sys.exit(0)
N = 256
gamma = [-1 for _ in range(N)]
done = [False for _ in range(N)]
revdone = [False for _ in range(N)]
notset = 256
pends = {}

def get_bounds(i):
    try:
        l = N - 1 - revdone.index(True, N - 1 - i) + 1
    except ValueError:
        l = 0
    try:
        r = done.index(True, i) - 1
    except ValueError:
        r = N - 1
    return (l, r)

def set_gamma(l, r, v):
    for i in range(l, r + 1):
        gamma[i] = v
        done[i] = True
        revdone[N - 1 - i] = True
for p in pis:
    if not done[p]:
        (lb, rb) = get_bounds(p)
        if lb > 0 and lb - 1 in pends and (lb - 1 + pends[lb - 1] >= p):
            l = lb
            r = p
            set_gamma(l, r, gamma[lb - 1])
            if r - l + 1 < pends[lb - 1]:
                pends[r] = pends[lb - 1] - (r - l + 1)
            del pends[lb - 1]
        else:
            l = max(p - k + 1, lb)
            r = p
            set_gamma(l, r, l)
            if r - l + 1 < k:
                pends[p] = k - (r - l + 1)
        notset -= r - l + 1
        if notset == 0:
            break
if notset > 0:
    for i in range(N):
        if gamma[i] < 0:
            (l, r) = get_bounds(i)
            set_gamma(l, min(l + k - 1, r), l)
print(' '.join((str(gamma[p]) for p in pis)))

Solution (Python):
def main():
    (n, k) = [int(_) for _ in input().split()]
    a = [int(_) for _ in input().split()]
    p = [-1] * 256
    p[0] = 0
    for x in a:
        if p[x] < 0:
            for y in range(x - 1, max(-1, x - k), -1):
                if p[y] >= 0:
                    if p[y] + k > x:
                        p[x] = p[y]
                    else:
                        p[x] = p[y + 1] = y + 1
                    break
            if p[x] < 0:
                p[x] = p[x - k + 1] = x - k + 1
    b = [p[x] for x in a]
    print(' '.join(map(str, b)))
if __name__ == '__main__':
    main()

Solution (Python):
def main():
    (n, k) = map(int, input().split())
    p = list(map(int, input().split()))
    solve(n, k, p)

def solve(n, k, p):
    group = 256 * [None]
    r = p[:]
    for (i, pi) in enumerate(p):
        if group[pi] is not None:
            r[i] = group[pi][0]
        else:
            lo = pi
            while lo >= 0 and pi - lo < k and (group[lo] is None):
                lo -= 1
            if lo < 0 or pi - lo == k:
                lo += 1
                hi = pi + 1
            elif pi - group[lo][0] < k:
                lo = group[lo][0]
                hi = pi + 1
            else:
                lo += 1
                hi = pi + 1
            lohi = (lo, hi)
            for j in range(lo, hi):
                group[j] = lohi
            r[i] = group[pi][0]
    print(' '.join(map(str, r)))
main()