Minimum path (Codeforces 1071B)
Tags: Greedy, hashing

You are given a matrix of size $$$n \times n$$$ filled with lowercase English letters. You can change no more than $$$k$$$ letters in this matrix.Consider all paths from the upper left corner to the lower right corner that move from a cell to its neighboring cell to the right or down. Each path is associated with the string that is formed by all the letters in the cells the path visits. Thus, the length of each string is $$$2n - 1$$$.Find the lexicographically smallest string that can be associated with a path after changing letters in at most $$$k$$$ cells of the matrix.A string $$$a$$$ is lexicographically smaller than a string $$$b$$$, if the first different letter in $$$a$$$ and $$$b$$$ is smaller in $$$a$$$.

Input: The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 2000$$$, $$$0 \le k \le n^2$$$) — the size of the matrix and the number of letters you can change.Each of the next $$$n$$$ lines contains a string of $$$n$$$ lowercase English letters denoting one row of the matrix.

Output: Output the lexicographically smallest string that can be associated with some valid path after changing no more than $$$k$$$ letters in the matrix.

Note: In the first sample test case it is possible to change letters 'b' in cells $$$(2, 1)$$$ and $$$(3, 1)$$$ to 'a', then the minimum path contains cells $$$(1, 1), (2, 1), (3, 1), (4, 1), (4, 2), (4, 3), (4, 4)$$$. The first coordinate corresponds to the row and the second coordinate corresponds to the column.

Sample Inputs:
4 2
abcd
bcde
bcad
bcde

5 3
bwwwz
hrhdh
sepsp
sqfaf
ajbvw

7 6
ypnxnnp
pnxonpm
nxanpou
xnnpmud
nhtdudu
npmuduh
pmutsnz

Sample Outputs:
aaabcde

aaaepfafw

aaaaaaadudsnz

Solution (Python):
import sys
input = lambda : sys.stdin.buffer.readline().decode().strip()
print = lambda *args, **kwargs: sys.stdout.write(' '.join(map(str, args)) + '\n', **kwargs)

def InputList(Dtype=int):
    return list(map(Dtype, input().split()))
from random import randint
RND = randint(1, 10 ** 9)
inf = float('inf')
from collections import deque

def solve():
    (N, k) = InputList()
    mat = [list(input()) for _ in range(N)]
    dp = [[inf] * N for _ in range(N)]
    dp[0][0] = 0
    for r in range(N):
        for c in range(N):
            dp[r][c] = min(dp[r][c], dp[r - 1][c], dp[r][c - 1]) + (mat[r][c] != 'a')
    if dp[-1][-1] <= k:
        return 'a' * (2 * N - 1)
    prefix = 0
    nxtPositions = []
    for r in range(N):
        for c in range(N):
            if dp[r][c] <= k:
                level = r + c + 1
                if level > prefix:
                    prefix = level
                    nxtPositions = []
                    if r + 1 < N:
                        nxtPositions.append((r + 1, c))
                    if c + 1 < N:
                        nxtPositions.append((r, c + 1))
                elif level == prefix:
                    if r + 1 < N:
                        nxtPositions.append((r + 1, c))
                    if c + 1 < N:
                        nxtPositions.append((r, c + 1))
    if not nxtPositions:
        nxtPositions = [(0, 0)]
    res = ['a'] * prefix
    for level in range(prefix, 2 * N - 1):
        bestChar = 'z'
        newPositions = []
        for (r, c) in nxtPositions:
            if mat[r][c] < bestChar:
                bestChar = mat[r][c]
                newPositions = []
                if r + 1 < N:
                    newPositions.append((r + 1, c))
                    dp[r + 1][c] = -1
                if c + 1 < N:
                    newPositions.append((r, c + 1))
                    dp[r][c + 1] = -1
            elif mat[r][c] == bestChar:
                if r + 1 < N and dp[r + 1][c] != -1:
                    newPositions.append((r + 1, c))
                    dp[r + 1][c] = -1
                if c + 1 < N and dp[r][c + 1] != -1:
                    newPositions.append((r, c + 1))
                    dp[r][c + 1] = -1
        res.append(bestChar)
        nxtPositions = newPositions
    return ''.join(res)
print(solve())

Solution (Python):
def main():
    (n, k) = readIntArr()
    arr = []
    for _ in range(n):
        arr.append(input())
    maxAinPath = [[0 for _ in range(n)] for __ in range(n)]
    for i in range(n):
        for j in range(n):
            if i > 0:
                maxAinPath[i][j] = max(maxAinPath[i][j], maxAinPath[i - 1][j])
            if j > 0:
                maxAinPath[i][j] = max(maxAinPath[i][j], maxAinPath[i][j - 1])
            if arr[i][j] == 'a':
                maxAinPath[i][j] += 1
    if maxAinPath[n - 1][n - 1] + k >= 2 * n - 1:
        print('a' * (2 * n - 1))
    else:
        potential = []
        for i in range(n):
            for j in range(n):
                if 1 + i + j == maxAinPath[i][j] + k:
                    potential.append([i, j])
        maxLen = -inf
        for (i, j) in potential:
            maxLen = max(maxLen, i + j)
        if maxLen == -inf:
            ans = []
        else:
            ans = ['a'] * (maxLen + 1)
        bfs = []
        for (i, j) in potential:
            if i + j == maxLen:
                bfs.append((i, j))
        if len(bfs) == 0:
            bfs.append((0, 0))
            ans.append(arr[0][0])
        while len(ans) < 2 * n - 1:
            bfs2 = set()
            for (i, j) in bfs:
                if i + 1 < n:
                    bfs2.add((i + 1, j))
                if j + 1 < n:
                    bfs2.add((i, j + 1))
            minLetter = 'z'
            for (i, j) in bfs2:
                letter = arr[i][j]
                minLetter = min(minLetter, letter)
            ans.append(minLetter)
            bfs = []
            for (i, j) in bfs2:
                if arr[i][j] == minLetter:
                    bfs.append((i, j))
            assert len(bfs) > 0
        print(''.join(ans))
    return
import sys
input = lambda : sys.stdin.readline().rstrip('\r\n')

def oneLineArrayPrint(arr):
    print(' '.join([str(x) for x in arr]))

def multiLineArrayPrint(arr):
    print('\n'.join([str(x) for x in arr]))

def multiLineArrayOfArraysPrint(arr):
    print('\n'.join([' '.join([str(x) for x in y]) for y in arr]))

def readIntArr():
    return [int(x) for x in input().split()]
inf = float('inf')
MOD = 10 ** 9 + 7
main()

Solution (Python):
def solve(m, matrix, good, n):
    c = 'z'
    for x in range(n):
        y = m - x
        if y < 0 or y >= n:
            continue
        if not good[x][y]:
            continue
        if x < n - 1:
            c = min(c, matrix[x + 1][y])
        if y < n - 1:
            c = min(c, matrix[x][y + 1])
    for x in range(n):
        y = m - x
        if y < 0 or y >= n:
            continue
        if not good[x][y]:
            continue
        if x < n - 1 and matrix[x + 1][y] == c:
            good[x + 1][y] = 1
        if y < n - 1 and matrix[x][y + 1] == c:
            good[x][y + 1] = 1
    return c

def main():
    (n, k) = map(int, input().split())
    matrix = []
    for i in range(n):
        s = list(input())
        matrix.append(s)
    dp = [[0 for i in range(n)] for j in range(n)]
    good = [[0 for i in range(n)] for j in range(n)]
    dp[0][0] = 0 if matrix[0][0] == 'a' else 1
    for i in range(1, n):
        dp[0][i] = dp[0][i - 1]
        if matrix[0][i] != 'a':
            dp[0][i] += 1
        dp[i][0] = dp[i - 1][0]
        if matrix[i][0] != 'a':
            dp[i][0] += 1
    for i in range(1, n):
        for j in range(1, n):
            dp[i][j] = min(dp[i - 1][j], dp[i][j - 1])
            if matrix[i][j] != 'a':
                dp[i][j] += 1
    m = -1
    for i in range(n):
        for j in range(n):
            if dp[i][j] <= k:
                m = max(m, i + j)
    if m == -1:
        print(matrix[0][0], end='')
        m = 0
        good[0][0] = 1
    else:
        for i in range(m + 1):
            print('a', end='')
        for i in range(n):
            y = m - i
            if y < 0 or y >= n:
                continue
            if dp[i][y] <= k:
                good[i][y] = 1
    while m < 2 * n - 2:
        res = solve(m, matrix, good, n)
        print(res, end='')
        m += 1
if __name__ == '__main__':
    main()