UVa 10003 - Cutting Sticks(区间DP+记忆化)

给出一个木棒和 m 个切点,每次切割需要花费等于当前木棒长度的费用。问最小花费。
对整个区间DP然后枚举区间的所有间断点。
转移方程为 d [ i ] [ j ] = m i n ( d [ i ] [ k ] + d [ k ] [ j ] ) 。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
const int maxn=55;
const int inf=0x3f3f3f3f;
int a[maxn],d[maxn][maxn];
int dp(int l,int r){
int& k=d[l][r];
if(l>=r-1) return k=0;
if(k!=inf) return k;
for(int i=l+1;i<r;++i)
k=min(k,dp(l,i)+dp(i,r)+a[r]-a[l]);
return k;
}
int main(){
int l,n;
while(~scanf("%d",&l)&&l){
memset(d,0x3f,sizeof(d));
scanf("%d",&n);
a[0]=0,a[n+1]=l;
for(int i=1;i<=n;++i) scanf("%d",&a[i]);
printf("The minimum cutting is %d.\n",dp(0,n+1));
}
return 0;
}

网上搜到的优化版本:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include <cstdio>
#include <cctype>
#include <cstring>
#include <algorithm>

using namespace std;

inline int Rint()
{
int c;
while(!isdigit(c = getchar()));
int t = c ^ 48;
while(isdigit(c = getchar()))
t = (t << 1) + (t << 3) + (c ^ 48);
return t;
}

const int N = 55;
int d[N][N], s[N][N], x[N];

int main()
{
for (int l; scanf("%d", &l) == 1 && l; )
{
int n = Rint();
for (int i = 1; i <= n; ++i) x[i] = Rint();
x[++n] = l;
for (int i = 0; i < n; ++i) d[i][i+1] = 0, s[i][i+1] = i;
for (int i = n - 2; i >= 0; --i)
for (int j = i + 2; j <= n; ++j)
{
int val = 2000000, p;
int st = max(s[i][j-1], i + 1), dt = min(s[i + 1][j], j - 1);
for (int k = st; k <= dt; ++k)
{
int t = d[i][k] + d[k][j];
if (t < val) val = t, p = k;
}
d[i][j] = val + x[j] - x[i], s[i][j] = p;
}
printf("The minimum cutting is %d.\n", d[0][n]);
}
return 0;
}

** 本文迁移自我的CSDN博客,格式可能有所偏差。 **