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) of n distinct elements such that e1 < e2 < ... < en and considering a binary search tree (see the previous problem) of the elements of S, 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 of S. 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 of S. Following n, in the same line, there will be n 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
直接推荐这个人的博客http://blog.youkuaiyun.com/shuangde800/article/details/11263763
AC代码如下:
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
int val[260],sum[260],dp[260][260],ret;
int main()
{ int n,m,i,j,k,l,r,d;
while(~scanf("%d",&n))
{ for(i=1;i<=n;i++)
{ scanf("%d",&val[i]);
sum[i]=sum[i-1]+val[i];
}
for(d=2;d<=n;d++)
for(l=1;l+d-1<=n;l++)
{ r=l+d-1;
ret=1000000000;
for(k=l;k<=r;k++)
ret=min(ret,dp[l][k-1]+dp[k+1][r]+sum[r]-sum[l-1]-val[k]);
dp[l][r]=ret;
}
printf("%d\n",dp[1][n]);
}
}

本文探讨了如何根据一组元素及其查询频率构建最优二叉搜索树的问题。文章提供了详细的输入输出示例,并附带了一段AC代码实现,该代码通过动态规划的方法计算出最优二叉搜索树的总成本。
1262

被折叠的 条评论
为什么被折叠?



