四边形不等式优化DP



4 1 4 5 1 2 4 2 4 5 1 2 0 0
17 2
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
typedef long long int LL;
const int maxn=1100;
int n,m;
LL a[maxn],sum[maxn];
LL dp[2][maxn],cost[maxn][maxn];
int s[2][maxn];
int main()
{
while(scanf("%d%d",&n,&m)!=EOF)
{
if(n==0&&m==0) break;
for(int i=1;i<=n;i++)
{
scanf("%I64d",a+i);
sum[i]=sum[i-1]+a[i];
}
memset(cost,0,sizeof(cost));
memset(s,0,sizeof(s));
for(int i=1;i<=n;i++)
for(int j=i+1;j<=n;j++)
cost[i][j]=cost[i][j-1]+(sum[j-1]-sum[i-1])*a[j];
memset(dp,63,sizeof(dp));
for (int i = 1; i <= n; ++i)
{
dp[0][i]=cost[1][i];
s[0][i]=1;
}
int now=1,pre=0;
for(int j=1;j<=m;j++)
{
s[now][n+1]=n-1;
for(int i=n;i>=j;i--)
{
for(int k=s[pre][i];k<=s[now][i+1];k++)
{
int temp=dp[pre][k]+cost[k+1][i];
if(temp<dp[now][i])
{
dp[now][i]=temp;
s[now][i]=k;
}
}
}
swap(now,pre);
}
printf("%I64d\n",dp[pre][n]);
}
return 0;
}
原文:http://blog.csdn.net/ck_boss/article/details/38785501