#P4381. Maximizing Bridge Walk in a Cyclic Park

    ID: 17627 Type: Default 1000ms 256MiB

Maximizing Bridge Walk in a Cyclic Park

Maximizing Bridge Walk in a Cyclic Park

You are planning to tour a park consisting of N islands. For each island i, a bridge of length \(L_i\) was built connecting island \(i\) to island \((i \bmod N) + 1\). The bridges are bidirectional. You may start your tour from any island and visit islands by walking across bridges, but each island can be visited at most once.

If you want to move from your current island \(S\) to an unvisited island \(D\), you have two options:

  • Walking: You can walk only if there is a direct bridge between \(S\) and \(D\); in this case, the bridge's length is added to your total walked distance.
  • Ferry: You may take a ferry if and only if there exists no way (using any combination of bridges and any previously used ferry rides) to travel from \(S\) to \(D\). Ferry rides do not add to your walked distance.

Since you prefer walking (which adds to your score), you want to maximize the total length of bridges you walk. Note that if you are able to walk using a bridge, you must do so instead of taking a ferry.

A key observation is that with the given construction, the islands form a cycle. For a cycle with \(N \ge 3\) islands the maximum walk is achieved by following a Hamiltonian path that omits exactly one bridge. To maximize the sum, you should omit the bridge with the smallest length. However, when \(N = 2\) the two islands are connected by two bridges, and since you cannot revisit an island, you can only walk one bridge, so the answer is the maximum of the two lengths.

Given the number of bridges and their lengths, compute the maximum total length of bridges you can walk.

inputFormat

The input consists of two lines:

The first line contains an integer (N) (where (N \ge 2)).

The second line contains (N) space-separated integers (L_1, L_2, \ldots, L_N) representing the lengths of the bridges.

outputFormat

Output a single integer—the maximum total length of bridges walked according to the rules.

sample

3
1 2 3
5