Hiking
Time limit10sMemory limit512 MB
Given directed step costs on a grid with no negative cycles, find the average shortest path over all ordered pairs of distinct cells, rounded up.
- Level
Hard8 of 10
- Topics
- Graph, Shortest path, Dynamic programming, Math
- Solved
- No attempts yet
Problem
Alice likes to hike. She likes some stretches of track and dislikes others, so the cost of walking a stretch records how she feels about it. Given a map with the cost of going from one cell to the next, find the average cost of a hike in that area.
The map is a rectangular grid of cells. Each cell carries the cost of taking one step from it to each of its northern, western, southern and eastern neighbours. A hike is a finite sequence of steps, each of which goes from a cell to one of its neighbours. The cost of a hike is the sum of the costs of its steps. A cost can be negative.
Once the start cell and the end cell are fixed, Alice always chooses a hike of minimum cost. Compute the average of those minimum costs over every ordered pair of distinct start and end cells. The start cell and the end cell must differ. A cost depends on the direction of travel, so and are different ordered pairs and each counts once. If several minimum-cost hikes join the same two cells, that pair still counts only once. The average therefore runs over exactly ordered pairs.
Input
The first line contains the width and the height of the map (). Rows are numbered to from the top and columns to from the left.
Each of the next lines contains integers. The -th integer on the -th of those lines is the cost of one step from cell to its northern neighbour , and it is between and .
Three more blocks of lines each follow, in the same format. They give the cost of a step to the western neighbour , then to the southern neighbour , then to the eastern neighbour .
Walking off the map is not allowed, and the corresponding entries are .
A minimum-cost hike exists between any two cells, so no sequence of steps returns to its starting cell with a negative total cost.
Output
Print on one line the smallest integer that is greater than or equal to the average cost of the minimum-cost hikes over all ordered pairs of distinct start and end cells.