Highways
Time limit1sMemory limit512 MB
Given N cities on a line with one-way roads only left to right, add two non-touching one-way roads to make the network strongly connected at minimum total length, or print 0.
- Level
Hard8 of 10
- Topics
- Greedy, Implementation, Math, Array
- Solved
- No attempts yet
Problem
In a distant country named Lineland there are cities, all lying along a single highway on a straight line. The highway starts at city 1, runs through city 2, city 3, and so on, and ends at city . City is located miles from city 1 (so , and the cities are ordered from left to right by number).
The highway is wide and smooth and a pleasure to drive, but every road in Lineland is one-way. People may drive along the highway only from a lower-numbered city toward a higher-numbered one; to get back they must use country roads, which is far less pleasant.
The new president wants to make travelling between cities easier, but he will not break tradition by making the highway two-way. Instead he will build new one-way highways so that, using only highways, one can get from any city to any other city (that is, so that the directed road network becomes strongly connected).
The president will build exactly two new highways. Each highway is a one-way road connecting two different cities. A new highway must not pass through any city other than the two it connects, and the four cities that serve as endpoints of the two highways must all be distinct.
You must choose which cities the two new highways connect. Since the cost of a highway is proportional to its length, the total length of the two highways must be as small as possible. Assume the length of a new highway between two cities equals the distance between those cities along the main highway.
Input
The first line contains the integer ().
The second line contains integers separated by spaces (). City 1 is always at position .
Output
If it is impossible to build the two highways satisfying all requirements, print .
Otherwise, print a single integer: the minimal possible total length of the two highways to be built.