NP-hard
Time limit2sMemory limit256 MB
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 to , 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 , every city with a smaller number is visited before city , or every one of them is visited after city . Placing one city smaller than before city 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 . ()
Each of the next lines has integers. The -th number on the -th line is the time needed to go from city to city , and it equals the -th number on the -th line. It is when and are the same, and an integer between and otherwise.
Output
Print the smallest total time needed to visit every city while obeying the rule.
Hint
Take the order with . The cities numbered below are and , city sits before city , and city sits after it, so this order breaks the rule. With only four orders obey it: , , , .