UVA 10003 Cutting Sticks

UVA_10003

    这是个区间的动态规划问题,首先我们可以补两个端点,然后就按区间长度递增的顺序进行递推即可,区间长度为1时的花费要初始化成0,其余初始化为INF。

    转移方程为f[i, j] = min{f[i, k] + f[k, j] + a[j] – a[i]}(i < k < j)。

#include<stdio.h>
#include<string.h>
#define MAXD 60
#define INF 100000000
int a[MAXD], N, L, f[MAXD][MAXD];
int init()
{
int i, j;
scanf("%d", &L);
if(!L)
return 0;
scanf("%d", &N);
a[0] = 0, a[N + 1] = L;
for(i = 1; i <= N; i ++)
scanf("%d", &a[i]);
return 1;
}
void solve()
{
int i, j, n, p, temp;
n = N + 1;
for(i = 0; i < n; i ++)
for(j = i + 1; j <= n; j ++)
{
if(i + 1 == j)
f[i][j] = 0;
else
f[i][j] = INF;
}
for(p = 2; p <= n; p ++)
for(i = 0; i + p <= n; i ++)
for(j = i + 1; j < i + p; j ++)
{
temp = f[i][j] + f[j][i + p] + a[i + p] - a[i];
if(temp < f[i][i + p])
f[i][i + p] = temp;
}
printf("The minimum cutting is %d.\n", f[0][n]);
}
int main()
{
while(init())
{
solve();
}
return 0;
}


你可能感兴趣的:(uva)