小白dp uva 10304 - Optimal Binary Search Tree

来源:互联网 发布:怎么获得淘宝代金券 编辑:程序博客网 时间:2024/06/06 01:58

10304 - Optimal Binary Search Tree

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


题意:

给你一个序列,构造出一棵最优查找树,输出权值。


思路:

开始想的为三维dp,左、右、层数,写了果断TLE,没想到怎么改进,看了题解恍然大悟。

其实第三维可以去掉,因为每加一层,在加之前就能统计额外所加的权值了,就是两个区间的总和,而不需要每层只算自己的。


感想:

有些时候真的自己怎么想也想不到,看一下题解马上就知道怎么做了,每次都差那么一点点,何时才能做到不看题解做出来呀。

每个题要能看出,每一步真正的改变了什么,然后再想怎么去处理。


代码:

#include <iostream>#include <cstdio>#include <cstring>#include <algorithm>#include <cmath>#include <string>#include <map>#include <stack>#include <vector>#include <set>#include <queue>#pragma comment (linker,"/STACK:102400000,102400000")#define maxn 305#define MAXN 100005#define mod 1000000007#define INF 0x3f3f3f3f#define pi acos(-1.0)#define eps 0.000001typedef long long ll;using namespace std;int n,m,ans,cnt,tot,flag;int a[maxn],sum[maxn];int dp[maxn][maxn];int dfs(int le,int ri){    if(le>ri) return 0;    if(dp[le][ri]!=INF) return dp[le][ri];    int i,j,t,best=INF;    for(i=le;i<=ri;i++)    {        best=min(best,dfs(le,i-1)+dfs(i+1,ri)+sum[i-1]-sum[le-1]+sum[ri]-sum[i]);    }    dp[le][ri]=best;    return best;}int main(){    int i,j,t;    while(~scanf("%d",&n))    {        sum[0]=0;        for(i=1;i<=n;i++)        {            scanf("%d",&a[i]);            sum[i]=sum[i-1]+a[i];        }        memset(dp,0x3f,sizeof(dp));        dfs(1,n);        printf("%d\n",dp[1][n]);    }    return 0;}/*1 53 10 10 103 5 10 20*/




0 0
原创粉丝点击