例题9-9 UVa10003 Cutting Sticks(DP:矩阵链乘)
题意:
看白书
要点:
明显是类似于矩阵连乘问题,用d[i][j]标记i到j中的最优费用,从中间一点k处截成两半,可以写出状态转移方程为d[i][j] = min(d[i][j], d[i][k] + d[k][j] + pos[j] - pos[i]),不难看出这实际是一个区间DP问题,通过j-i小区间不断递增进行DP,注意这里i和j不用写成0~len,因为d[i][j]只是起到一个存储状态的作用,i和j应用来表示n个切割点的数组下标。
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<algorithm>
using namespace std;
int len;
int pos[65],d[65][65];
int main()
{
int i, j, k,l;
while (scanf("%d", &len) && len)
{
int n;
scanf("%d", &n);
for (i = 1; i <= n; i++)
scanf("%d", &pos[i]);
pos[0] = 0; pos[n + 1] = len;//补上两个切割点
for (i = 0; i <= n + 1; i++)
d[i][i] = 0;
for (l = 2; l <= n+1; l++)//这里实际i和j表示切割点对应下标即可
{
for (i = 0; i+l <=n+1; i++)
{
j = i + l;
d[i][j] = 0xfffff;
for (k = i+1; k < j; k++)
d[i][j] = min(d[i][j], d[i][k] + d[k][j] + pos[j] - pos[i]);
}
}
printf("The minimum cutting is ");
printf("%d.\n", d[0][n+1]);
}
return 0;
}