Moortal Cowmbat

Time limit1sMemory limit512 MB

Summary
Rewrite a length-N string into streaks of at least K identical letters, where changing any single position from letter i to j costs a shortest-path distance over an M-letter graph; minimize total cost.
Level

Medium7 of 10

Topics
Dynamic programming, Shortest path, Prefix sum, Graph
Solved
No attempts yet

Problem

Bessie has been playing the popular fighting game Moortal Cowmbat for a long time. However, the game developers have recently rolled out an update that forces Bessie to change her play style.

The game uses MM buttons labeled by the first MM lowercase letters (1≤M≤261 \leq M \leq 26). Bessie's favorite combo in the game is a length-NN string SS of button presses (1≤N≤1051 \leq N \leq 10^5). Because of the most recent update, every combo must now be made from a series of "streaks", where a streak is a series of the same button pressed at least KK times in a row (1≤K≤N1 \leq K \leq N). Bessie wants to modify her favorite combo into a new combo of the same length NN that is made from streaks of button presses, so that it satisfies the changed rules.

Bessie needs aija_{ij} days to train herself to press button jj instead of button ii at any specific location in her combo. That is, it costs aija_{ij} to change a single specific letter in SS from ii to jj. Switching from button ii to an intermediate button kk and then from button kk to button jj may take less time than switching from ii to jj directly. More generally, there may be a path of changes that starts at ii and ends at jj and gives the best overall cost for switching from button ii ultimately to button jj.

Help Bessie determine the smallest possible number of days she needs to create a combo that satisfies the new requirements.

Input

The first line of input contains NN, MM, and KK. The second line contains SS, and the final MM lines contain an M×MM\times M matrix of values aija_{ij}, where aija_{ij} is an integer in the range 0…10000 \ldots 1000 and aii=0a_{ii} = 0 for all ii.

Output

Output a single number, representing the minimum number of days Bessie needs to change her combo into one that satisfies the new requirements.

Hint

The optimal solution in this example is to change the a into b, change the d into e, and then change both e's into c's. This takes 1+4+0+0=51+4+0+0=5 days, and the final combo string is bbccc.

Examples1

  1. Example 1

    Input
    5 5 2
    abcde
    0 1 4 4 4
    2 0 4 4 4
    6 5 0 3 2
    5 5 5 0 4
    3 7 0 5 0
    
    Expected output
    5