uva10304 Optimal Binary Search Tree(DP)

题目链接:http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=11&page=show_problem&problem=1245

 

#include <iostream>
#include <cstdio>
#define ll long long
using namespace std;
ll v[300],sum[300];
ll dp[300][300];
int n;
ll DP(int x,int y){
   if(dp[x][y]!=(ll)1e17) return dp[x][y];
   if(x==y) return dp[x][y]=0;
   ll ret=(ll)1e17;
   for(int i=x;i<=y;i++){
       if(i==x) ret=min(ret,DP(i+1,y)+sum[y]-sum[i]);
       else if(i==y) ret=min(ret,DP(x,i-1)+sum[i-1]-sum[x-1]);
       else ret=min(ret,DP(x,i-1)+DP(i+1,y)+sum[y]-sum[x-1]-v[i]);
   }
   return dp[x][y]=ret;
}
int main(){
    while(cin>>n){
        for(int i=1;i<=n;i++) cin>>v[i];
        sum[0]=0;
        for(int i=1;i<=n;i++) sum[i]=sum[i-1]+v[i];
        for(int i=0;i<300;i++){
           for(int j=0;j<300;j++){
              dp[i][j]=(ll)1e17;
           }
        }
        cout<<DP(1,n)<<endl;
    }
    return 0;
}
uva10304

 

posted @ 2014-02-09 20:42  wonderzy  阅读(172)  评论(0编辑  收藏  举报