#Q150. 「一本通 5.1 例 2」能量项链
「一本通 5.1 例 2」能量项链
Description
Original source: NOIP 2006
On the planet Mars, every Martian wears a string of energy necklaces. The necklace has energy beads. Each bead has a head mark and a tail mark, which correspond to some positive integers. Moreover, for any two adjacent beads, the tail mark of the previous bead must equal the head mark of the next bead. Only under this condition can the two beads be merged into one through the action of a sucker—the organ Martians use to absorb energy. If the head mark of one bead is , the tail mark is , and the head mark of the next bead is with a tail mark of , then merging them releases units of Mars energy. The new bead will have a head mark of and a tail mark of .
When needed, Martians use suckers to clamp two adjacent beads, merging them to obtain energy until only one bead remains on the necklace. Clearly, different merging orders yield different total energy outputs. Design a merging sequence that maximizes the total energy released from the necklace.
For example, let , with the four beads' head and tail marks as . We denote the merging operation of two beads by , where represents the energy released by merging beads and . The energy released by merging the th and st beads is . An optimal merging sequence for this necklace releases a total energy of $10\times 2\times 3+10\times 3\times 5+10\times 5\times 10=710$.
Now, given a necklace with beads, where adjacent beads can be merged into one, each merge releases a certain amount of energy, and different merges release different amounts of energy, what is the optimal merging order to maximize the total energy released?
Input Format
The first line contains a positive integer .
The second line contains positive integers not exceeding , where the -th number is the head mark of the -th bead. When , the tail mark of the -th bead equals the head mark of the -th bead. When , the tail mark of the -th bead equals the head mark of the st bead.
As for the order of the beads, you can determine it as follows: place the necklace on a flat surface without any crossings, randomly designate one bead as the first, and determine the order of the other beads clockwise.
Output Format
Output only one line, a positive integer not exceeding , representing the maximum total energy released by the optimal merging sequence.
Sample 1
4
2 3 5 10
710
Data Range and Hints
For of the data, .