Baltic OI '07 P6 - Sequence

View as PDF

Submit solution


Points: 12 (partial)
Time limit: 0.6s
Memory limit: 64M

Problem type
Baltic Olympiad in Informatics: 2007 Day 2, Problem 3

We are given a sequence a1,,an. We can manipulate this sequence using the operation reduce(i), which replaces elements ai and ai+1 with a single element max(ai,ai+1), resulting in a new shorter sequence. The cost of this operation is max(ai,ai+1). After n1 reduce operations, we obtain a sequence of length 1. Our task is to compute the cost of the optimal reducing scheme, i.e. the sequence of reduce operations with minimal cost leading to a sequence of length 1.

Constraints

1n106

0ai109

Subtask 1 [30%]

1n500

Subtask 2 [20%]

1n2×104

Subtask 3 [50%]

No additional constraints.

Input Specification

The first line of input contains an integer n, the length of the sequence. The following n lines contain one integer ai, the elements of the sequence.

Output Specification

Output the minimal cost of reducing the sequence to a single element.

Sample Input

Copy
3
1
2
3

Sample Output

Copy
5

Explanation for Sample Output

The optimal way to reduce the array to one element has a cost of max(1,2)+max(2,3):

  • [1, 2, 3] → [2, 3]
  • [2, 3] → [3]

Comments

There are no comments at the moment.