UVa 10003 - Cutting Sticks

记忆化搜索;

需要判断当前状态是否被更新。

# include <stdio.h>
# include <string.h>

# define INF 20000

int l, n;
int s[54];
int f[55][55];

int dp(int i, int j);

int main()
{
int i, j;

while (1)
{
scanf("%d", &l);
if (l == 0) break;
scanf("%d", &n);
if (l == 0) break;
for (i = 1; i <= n; ++i)
scanf("%d", &s[i]);
s[0] = 0; s[n+1] = l;
printf("The minimum cutting is %d.\n", dp(0, n+1));
memset(f, 0, sizeof(f));
}

return 0;
}

int dp(int i, int j)
{
int k;
if (f[i][j] > 0) return f[i][j];
if (i+1 == j) return f[i][j] = 0;
for (f[i][j] = INF, k = i + 1; k < j; ++k)
if (f[i][j] > dp(i, k) + dp(k, j))
f[i][j] = dp(i, k) + dp(k, j);
if (f[i][j] >= INF) f[i][j] = 0; // 一次这里没加判断导致的WA,不是很理解
f[i][j] += s[j] - s[i];
return f[i][j];
}

你可能感兴趣的:(uva)