Tube Master II
Time limit2sMemory limit512 MB
Pick tube segments so each crossing uses either nothing or one horizontal and one vertical tube, meeting every cell's required count at minimum total cost.
- Level
Hard8 of 10
- Topics
- Dynamic programming, Bit manipulation, Matrix
- Solved
- No attempts yet
Problem
Yuuka is playing "Tube Master". The game field is divided into cells and crossings. The crossings are connected by horizontal tubes and vertical tubes. The cells are labeled for , , and the crossings are labeled for , . Each cell contains an integer .

Yuuka decides to use some of the tubes, subject to these restrictions:
- Either 0 or 2 tubes connected to each crossing are used.
- No two consecutive horizontal tubes are used at the same time, and no two consecutive vertical tubes are used at the same time. Two tubes are consecutive if and only if they share a crossing.
- Exactly of the tubes surrounding cell are used.
Using the tube connecting crossings and costs . Using the tube connecting crossings and costs . Find a configuration that satisfies the restrictions with the minimum total cost.
Input
The input contains zero or more test cases and ends at end-of-file. For each test case:
The first line contains two integers and ().
The -th of the following lines contains integers ().
The -th of the next lines contains integers .
The -th of the last lines contains integers .
The constraints are . The sum of over all test cases does not exceed .
Output
For each test case, output the minimum cost of a valid configuration. If no valid configuration exists, output "-1" instead.