This page is still under construction.

Parts of this page are still being built. What you see may change.

Deserter Pursuit

Time limit3sMemory limit512 MB

Summary
Given an N x N grid with one base, up to five deserters, and toll cells that charge each time you enter, find the minimum total toll to start at the base, visit every deserter, and return.
Level

Medium7 of 10

Topics
Graph, Shortest path, Dynamic programming, Bit manipulation
Solved
No attempts yet

Problem

The Deserter Pursuit (DP) is a unit of soldiers who track down and arrest deserters.

One day, Hoyul, a member of the Deserter Pursuit, is given operating funds and a map, along with orders to catch all the deserters and return to base. Hoyul wants to save money to buy bagged ramen, so he tries to catch all the deserters while spending as little of the operating funds as possible.

The map is an N×NN \times N grid. The positions of the base and the deserters are given on the map, and every other cell that does not contain the base or a deserter contains a tollgate.

Each tollgate has a fixed toll, and to visit a cell with a tollgate, Hoyul must pay the toll. Also, visiting the same cell multiple times requires paying the toll each time.

Hoyul must start at the base, catch all the deserters, and return, and he may stop by the base in the middle. He can move one cell at a time to an adjacent cell up, down, left, or right, and he cannot go anywhere other than the spaces shown on the map.

For Hoyul, who wants to do nothing, compute the minimum cost to start at the base, catch all the deserters, and return to the base.

Input

The first line gives the size of the grid NN. (5≤N≤1,0005 \le N \le 1,000)

The next NN lines give the map. −1-1 is the base, 00 is a deserter, and an integer of 11 or more is the toll of a tollgate; every toll is an integer of 1,0001,000 or less.

The input contains exactly one base, and the number of deserters is at most 5.

There may be no deserters.

Output

On the first line, output the answer to the problem.

Examples2

  1. Example 1

    Input
    5
    1 3 2 0 9
    2 0 4 4 3
    5 3 -1 1 1
    3 7 2 0 1
    1 2 3 5 0
    
    Expected output
    16
    
  2. Example 2

    Input
    5
    1 3 2 4 9
    2 2 4 4 3
    5 3 -1 1 1
    3 7 2 7 1
    1 2 3 5 9
    
    Expected output
    0