This page is still under construction.

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

Highways

Time limit1sMemory limit512 MB

Summary
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 NN 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 NN. City ii is located XiX_i miles from city 1 (so X1=0X_1 = 0, 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 NN (2≤N≤50 0002 \le N \le 50\,000).

The second line contains N−1N-1 integers X2,X3,…,XNX_2, X_3, \ldots, X_N separated by spaces (1≤X2<X3<⋯<XN≤1091 \le X_2 < X_3 < \cdots < X_N \le 10^9). City 1 is always at position X1=0X_1 = 0.

Output

If it is impossible to build the two highways satisfying all requirements, print 00.

Otherwise, print a single integer: the minimal possible total length of the two highways to be built.

Examples3

  1. Example 1

    Input
    4
    3 5 10
    
    Expected output
    12
    
  2. Example 2

    Input
    2
    1
    
    Expected output
    0
    
  3. Example 3

    Input
    5
    2 4 7 8
    
    Expected output
    10