408285: GYM103076 H 8 Game
Description
The 8 game consists of a 3x3 matrix. Each cell has a distinct number between 1 and 8 or a white space.
Let $$$M$$$ be the given matrix, if $$$M_{i,j} == 0$$$, then you can do four operations:
- Swap $$$M_{i,j}$$$ with $$$M_{i,j+1}$$$, if $$$j < 3$$$
- Swap $$$M_{i,j}$$$ with $$$M_{i,j-1}$$$, if $$$j > 1$$$
- Swap $$$M_{i,j}$$$ with $$$M_{i+1,j}$$$, if $$$i < 3$$$
- Swap $$$M_{i,j}$$$ with $$$M_{i-1,j}$$$, if $$$i > 1$$$
Let's assume you swapped $$$M_{i,j}$$$ with $$$M_{i',j'}$$$, and let $$$x == M_{i',j'}$$$, then this operation has $$$Cost_x$$$ of cost.
$$$Cost_x$$$ is the swap cost for each number $$$x$$$, $$$1 <= x <= 8$$$.
Kinho loves the 8 game, but now he is very busy developing his 3D game library, so he asks you to solve this problem.
Given the initial matrix and the cost to move each number, say what is the minimum cost necessary to order the matrix in the requested way.
InputThe input consists of four lines. The three initial lines contains three distincts integers each. $$$0 <= M_{i,j} <= 8$$$, where $$$0$$$ represents a white space cell. The fourth line contains eight integers, where the $$$i$$$-th integer represents the cost $$$Cost_i$$$ to swap the cell with the number $$$i$$$. $$$1 <= Cost_i <= 10^9, 1 <= i <= 8$$$
OutputPrint a single integer, the minimum cost to reorganize the matrix. In the given input, there is always a valid answer.
ExamplesInput5 4 0 6 1 8 7 3 2 1 1 1 1 1 1 1 1Output
22Input
1 2 3 4 5 6 7 8 0 1 1 1 1 1 1 1 1Output
0