This page is still under construction.

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

NP-hard

Time limit2sMemory limit256 MB

Summary
Find the shortest route that visits each of up to 1500 cities once when every city keeps all lower-numbered cities on one side of it.
Level

Medium7 of 10

Topics
Dynamic programming, Intervals
Solved
No attempts yet

Problem

The travelling salesman problem is NP-hard, so no fast method is known once the number of cities grows. Here you solve a variant that adds one rule about the visiting order.

The cities are numbered 11 to NN, and the travel time between every pair of cities is given. Visit every city exactly once and make the total travel time as small as possible.

The rule is this. When you visit city KK, every city with a smaller number is visited before city KK, or every one of them is visited after city KK. Placing one city smaller than KK before city KK and another one after it is not allowed.

You may start at any city and finish at any city. Only the times between neighbouring cities in the visiting order are added up, and the trip back from the last city to the first one is not counted.

Write a program that finds the smallest total time of a visiting order that obeys the rule.

Input

The first line has the number of cities NN. (2≤N≤15002 \le N \le 1500)

Each of the next NN lines has NN integers. The BB-th number on the AA-th line is the time needed to go from city AA to city BB, and it equals the AA-th number on the BB-th line. It is 00 when AA and BB are the same, and an integer between 11 and 10001000 otherwise.

Output

Print the smallest total time needed to visit every city while obeying the rule.

Hint

Take the order 1,3,21, 3, 2 with N=3N = 3. The cities numbered below 33 are 11 and 22, city 11 sits before city 33, and city 22 sits after it, so this order breaks the rule. With N=3N = 3 only four orders obey it: (1,2,3)(1, 2, 3), (3,2,1)(3, 2, 1), (2,1,3)(2, 1, 3), (3,1,2)(3, 1, 2).

Examples2

  1. Example 1

    Input
    3
    0 5 2
    5 0 4
    2 4 0
    
    Expected output
    7
    
  2. Example 2

    Input
    4
    0 15 7 8
    15 0 16 9
    7 16 0 12
    8 9 12 0
    
    Expected output
    31