uva10304 Optimal Binary Search Tree

来源:互联网 发布:算法工程师考试时间 编辑:程序博客网 时间:2024/05/19 09:02

Given a set S
= ( e 1 ;e 2 ;:::;e n ) of n distinct elements such that e 1 < e 2 <:::< e n 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 e i of S in a tree ( cost ( e i )) 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 ( e 1 ) ;f ( e 2 ) ;:::;f ( e n )), we say that the total
cost of a tree is the following summation: f ( e 1 )  cost ( e 1 ) +
f ( e 2 )  cost ( e 2 ) + :::
+ f ( e n )  cost ( e n ) 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 ( e 1 ) ;f ( e 2 ) ;:::;f ( e n ), 0  f ( e i ) 
100. Input is terminated by end of le. 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.

区间dp,枚举区间i..j的根节点x,dp[i][j]=min{dp[i][x-1]+dp[x+1][j]+s[j]-s[i-1]-a[x]},其中s为前缀和。

#include<cstdio>#include<cstring>#include<algorithm>using namespace std;int dp[260][260],a[260],s[260],n;int main(){    int i,j,k,p,q,x,y,z;    while (scanf("%d",&n)==1)    {        memset(dp,0x3f,sizeof(dp));        dp[n+1][n]=0;        for (i=1;i<=n;i++)        {            scanf("%d",&a[i]);            s[i]=s[i-1]+a[i];            dp[i][i]=dp[i][i-1]=0;        }        for (k=2;k<=n;k++)          for (i=1;(j=i+k-1)<=n;i++)            for (x=i;x<=j;x++)              dp[i][j]=min(dp[i][j],dp[i][x-1]+dp[x+1][j]+s[j]-s[i-1]-a[x]);        printf("%d\n",dp[1][n]);    }}
0 0
原创粉丝点击