Optimal Binary Search Tree
Given a set of distinct elements such that and considering a binary search tree of the elements of , it is desired that higher the query frequency of an element, closer will it be to the root.
The of accessing an element of in a tree is equal to the number of edges in the path that connects the root with the node that contains the element. Given the query frequencies of the elements of , , we say that the total cost of a tree is the following summation:
In this manner, the tree with the lowest total cost is the one with the best representation for searching elements of . Because of this, it is called the Optimal Binary Search Tree.
Input
Contains several instances, one per line. Each line will start with a number , indicating the size of . Following , in the same line, there will be non-negative integers representing the query frequencies of the elements of : .
Output
For each test case print a line with the total cost of the Optimal Binary Search Tree.