E59 四边形不等式优化DP Optimal Binary Search Tree

视频链接:474 四边形不等式优化DP Optimal Binary Search Tree_哔哩哔哩_bilibili

UVA10304 Optimal Binary Search Tree

Luogu UVA10304 Optimal Binary Search Tree

 

#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;

const int N=300;
int n, e[N], s[N];
int f[N][N];//f[i,j]表示给区间[i,j]建排序二叉树的最小费用

int main(){
  while(~scanf("%d",&n)){
    for(int i=1; i<=n; i++)
      scanf("%d",&e[i]), s[i]=s[i-1]+e[i];
      
    memset(f,0x3f, sizeof f);
    for(int i=1;i<=n;i++) f[i][i]=f[i][i-1]=f[i+1][i]=0;
    
    for(int len=2; len<=n; len++)
      for(int i=1,j; (j=i+len-1)<=n; i++)
        for(int k=i; k<=j; k++)
          if(f[i][j]>f[i][k-1]+f[k+1][j]+s[j]-s[i-1]-e[k])
             f[i][j]=f[i][k-1]+f[k+1][j]+s[j]-s[i-1]-e[k];
    printf("%d\n", f[1][n]);
  }
}

 

#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;

const int N=300;
int n,e[N],s[N];
int f[N][N];//f[i,j]表示给区间[i,j]建排序二叉树的最小费用
int p[N][N];//p[i,j]表示状态f[i,j]的最优决策点

int main(){
  while(~scanf("%d",&n)){
    for(int i=1; i<=n; i++)
      scanf("%d",&e[i]),s[i]=s[i-1]+e[i];
    
    memset(f,0x3f,sizeof(f));
    for(int i=1; i<=n; i++)
      f[i][i]=f[i+1][i]=f[i][i-1]=0, p[i][i]=i;
    
    for(int len=2; len<=n; len++)
      for(int i=1,j; (j=i+len-1)<=n; i++)
        for(int k=p[i][j-1]; k<=p[i+1][j]; k++)
          if(f[i][j]>f[i][k-1]+f[k+1][j]+s[j]-s[i-1]-e[k])
            f[i][j]=f[i][k-1]+f[k+1][j]+s[j]-s[i-1]-e[k], p[i][j]=k;
    printf("%d\n",f[1][n]);
  }
}

 

练习:

CF868F Yet Another Minimization Problem

 

posted @ 2023-05-28 10:51  董晓  阅读(220)  评论(0编辑  收藏  举报