uva10304 Optimal Binary Search Tree

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
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值