Containers

Place eight weights into a 2x4 grid; swapping two adjacent cells costs the sum of the two weights, and you must reach the target arrangement at minimum total cost.

Medium7GraphBFSShortest pathImplementationNo attempts yetTime limit1sMemory limit512 MB

Problem

The container balancing system (SBC) has to be updated for a new class of ship, the "two by four", which carries eight large containers in two rows and four columns. Each of these ships has a fixed crane that performs exactly one kind of move: it lifts two containers that are adjacent in the same row or in the same column and exchanges their positions.

To finish loading quickly at the port, the eight containers go into any of the eight positions. The arrangement that results is the initial configuration. Once the ship leaves the port, the crane has to move the containers into a final configuration that was fixed in advance for the voyage.

The fuel cost of one crane move equals the sum of the weights of the two containers whose positions were exchanged. Given the weight sitting in every position of the initial configuration and of the final configuration, compute the smallest possible total cost of a sequence of moves that turns the initial configuration into the final one.

Input

Four lines are given, each with four integers. Every integer is between 1 and 1000, inclusive. The first two lines hold the weights of the initial configuration and the last two lines hold the weights of the final configuration. A solution always exists, because the containers of the two configurations are the same and only their positions may differ.

Output

Print one line with a single integer, the minimum total cost of a sequence of moves that goes from the initial configuration to the final one.