Whitespace

Given the line lengths of a Whitespace program and a RETURN key that duplicates the current line's spaces, find the minimum key presses to build the text from a single newline.

Medium6Dynamic programmingGreedyImplementationNo attempts yetTime limit2sMemory limit512 MB

Problem

Whitespace is a programming language whose programs consist only of spaces and line breaks. A space is written as SP and a line break as NL.

Yeongseon has a program written in Whitespace. It can be described by a sequence LL of length NN: LiL_i is the number of SP characters on line ii, and every line ends with NL. In other words, the source code is L0L_0 copies of SP, then NL, then L1L_1 copies of SP, then NL, \ldots, then LN1L_{N-1} copies of SP, then NL.

Today Yeongseon wants to type the program using an editor that Hyobin made. The cursor can be placed at the start or the end of the document, or between any two adjacent characters. Moving the cursor costs no key presses.

The editor has the following 3 special keys.

  • SPACE: inserts one SP at the cursor position.
  • DELETE: deletes the SP immediately to the right of the cursor. It cannot be used when the character to the right is NL.
  • RETURN: types one NL and then KK copies of SP, where KK is the number of SP characters on the line containing the cursor. It can be used only when the character immediately to the right of the cursor is NL. For example, if the document is SP NL SP SP NL SP SP SP NL and RETURN is pressed right before the second NL, the document becomes SP NL SP SP NL SP SP NL SP SP SP NL.

The editor currently contains a single NL. Given LL, write a program that finds the minimum number of key presses needed to complete the source code.

Input

The first line contains NN. The second line contains L0,L1,,LN1L_0, L_1, \ldots, L_{N-1}, separated by spaces.

  • 1N501 \le N \le 50
  • 0Li10000000 \le L_i \le 1\,000\,000

Output

Print the minimum number of key presses needed to complete the source code on the first line.

Hint

In the first example, the document can be completed with 6 key presses as follows.

  • NL
  • SP NL
  • SP SP NL
  • SP SP SP NL
  • SP SP SP NL SP SP SP NL
  • SP SP SP NL SP SP SP NL SP SP SP NL
  • SP SP SP NL SP SP NL SP SP SP NL