uva 10304 Optimal Binary Search Tree(DP)

来源:互联网 发布:网络的好处和坏处 编辑:程序博客网 时间:2024/05/16 10:57

Problem E

Optimal Binary Search Tree

Input: standard input

Output: standard output

Time Limit: 30 seconds

Memory Limit: 32 MB

Given a set S = (e1, e2, ..., en) ofn distinct elements such that e1 < e2 < ... < en and considering a binary search tree (see the previous problem) of the elements ofS, it is desired that higher the query frequency of an element, closer will it be to the root.

The cost of accessing an element ei of S in a tree (cost(ei)) 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 S, (f(e1), f(e2, ..., f(en)), we say that the total cost of a tree is the following summation:

f(e1)*cost(e1) + f(e2)*cost(e2) + ... + f(en)*cost(en)

In this manner, the tree with the lowest total cost is the one with the best representation for searching elements ofS. Because of this, it is called the Optimal Binary Search Tree.

Input

The input will contain several instances, one per line.

Each line will start with a number 1 <= n <= 250, indicating the size ofS. Following n, in the same line, there will ben non-negative integers representing the query frequencies of the elements of S:f(e1), f(e2), ..., f(en). 0 <= f(ei) <= 100. Input is terminated by end of file.

Output

For each instance of the input, you must print a line in the output with the total cost of the Optimal Binary Search Tree.

Sample Input

1 5
3 10 10 10
3 5 10 20

Sample Output

0
20
20
#include <iostream>#include <cstdio>using namespace std;const int maxn = 300;int num[maxn] , n;int sum[maxn][maxn] , dp[maxn][maxn];void initial(){for(int i = 0;i < maxn;i++){for(int j = 0;j < maxn;j++){dp[i][j] = 0;sum[i][j] = 0;}num[i] = 0;}}void readcase(){for(int i = 1;i <= n;i++){cin >> num[i];sum[i][i] = num[i];}for(int i = 1;i <= n;i++){for(int j = i+1;j <= n;j++){sum[i][j] = sum[i][j-1]+num[j];//cout << i << " " << j << ":" << sum[i][j] << endl;}}}void computing(){for(int k = 1;k < n;k++){for(int i = 1;i+k <= n;i++){dp[i][i+k] = dp[i+1][i+k]+sum[i+1][i+k];for(int j = i+1;j <= i+k;j++){int t = dp[i][j-1]+sum[i][j-1]+dp[j+1][i+k]+sum[j+1][i+k];//cout << j <<":" <<t <<" " << dp[i][i+k]<< endl;if(dp[i][i+k] > t){dp[i][i+k] = t;//cout << i << " " << i+k << " " << j <<":" <<dp[i][i+k] << endl;}}}}//cout << dp[1][n] << endl;cout << dp[1][n] << endl;}int main(){while(cin >> n){initial();readcase();computing();}return 0;}


0 0
原创粉丝点击