紫书动规 例题9-9 UVA - 10003 Cutting Sticks 区间dp
题目链接:
https://vjudge.net/problem/UVA-10003
题意:
题解:
dp[i][j]:=切割小木棍i~j的最优费用,枚举中间切割点,这段的费用是该段的长度
d[i][j] = min(d[i][j],dp(i,k)+dp(k,j)+a[j]-a[i]);
代码:
1 #include <bits/stdc++.h> 2 using namespace std; 3 typedef long long ll; 4 #define MS(a) memset(a,0,sizeof(a)) 5 #define MP make_pair 6 #define PB push_back 7 const int INF = 0x3f3f3f3f; 8 const ll INFLL = 0x3f3f3f3f3f3f3f3fLL; 9 inline ll read(){ 10 ll x=0,f=1;char ch=getchar(); 11 while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();} 12 while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();} 13 return x*f; 14 } 15 ////////////////////////////////////////////////////////////////////////// 16 const int maxn = 1e5+10; 17 18 int len,n; 19 int a[maxn]; 20 int d[100][100]; 21 22 int dp(int i,int j){ 23 if(i+1 == j) return 0; 24 if(d[i][j] != INF) return d[i][j]; 25 26 for(int k=i+1; k<j; k++){ 27 d[i][j] = min(d[i][j],dp(i,k)+dp(k,j)+a[j]-a[i]); 28 } 29 return d[i][j]; 30 } 31 32 int main(){ 33 while(cin>>len && len){ 34 cin >> n; 35 for(int i=1; i<=n; i++) 36 a[i] = read(); 37 a[0] = 0; a[n+1] = len; 38 39 // dp[i][j] = dp[i][k]+dp[k][j]; 40 for(int i=0; i<=n+1; i++) 41 for(int j=0; j<=n+1; j++) 42 d[i][j] = INF; 43 printf("The minimum cutting is %d.\n", dp(0,n+1)); 44 } 45 return 0; 46 }