状态转移
d(i,j) 为切割小木棍i~j的最优费用
d(i,j) = min{d(i,k)+d(k+j)|i<k<j}+a[j]-a[i]
1 #include <bits/stdc++.h> 2 using namespace std; 3 4 5 const int maxn = 50+5; 6 int L,n,vis[maxn][maxn],d[maxn][maxn],a[maxn]; 7 8 9 int dp(int i,int j){ 10 if(i >= j-1) return 0; 11 if(vis[i][j]) return d[i][j]; 12 vis[i][j] = 1; 13 d[i][j] = -1; 14 for(int k=i+1; k<j; k++){ 15 int v = dp(i,k) + dp(k,j) + a[j] - a[i]; 16 if(d[i][j]<0 || v<d[i][j]) d[i][j] = v; 17 } 18 19 return d[i][j]; 20 } 21 22 int main(){ 23 while(cin>>L && L){ 24 cin >> n; 25 memset(vis,0,sizeof(vis)); 26 for(int i=1; i<=n; i++){ 27 cin >> a[i]; 28 } 29 a[0] = 0,a[n+1] = L; 30 cout << "The minimum cutting is " << dp(0,n+1) << "." << endl; 31 } 32 }