题意:有一根长度为L(L<1000)的棍子,还有n(n < 50)个切割点的位置(按照从小到大排列)。你的任务是在这些切割点的位置处把棍子切成n+1部分,使得总切割费用最小。每次切割的费用等于被切割的木棍长度。
分析:
1、solve(i, j)为切割小木棍i~j的最优费用。
2、设k(i<k<j),solve(i, j) = min{solve(i, k) + solve(k, j)} + a[j] - a[i]。
k是切割小木棍i~j费用最优的切割点,a[j] - a[i] 为小木棍i ~ j 的长度,即切割小木棍i~j的费用。
3、将小木棍的n个切割点标记为1~n,左端点为0,右端点为n + 1,则答案为solve(0, n + 1)。
4、注意L和n个切割点的位置都是positive number,所以可能是浮点数。
#pragma comment(linker, "/STACK:102400000, 102400000") #include<cstdio> #include<cstring> #include<cstdlib> #include<cctype> #include<cmath> #include<iostream> #include<sstream> #include<iterator> #include<algorithm> #include<string> #include<vector> #include<set> #include<map> #include<stack> #include<deque> #include<queue> #include<list> #define Min(a, b) ((a < b) ? a : b) #define Max(a, b) ((a < b) ? b : a) const double eps = 1e-8; inline int dcmp(double a, double b){ if(fabs(a - b) < eps) return 0; return a > b ? 1 : -1; } typedef long long LL; typedef unsigned long long ULL; const int INT_INF = 0x3f3f3f3f; const int INT_M_INF = 0x7f7f7f7f; const LL LL_INF = 0x3f3f3f3f3f3f3f3f; const LL LL_M_INF = 0x7f7f7f7f7f7f7f7f; const int dr[] = {0, 0, -1, 1, -1, -1, 1, 1}; const int dc[] = {-1, 1, 0, 0, -1, 1, -1, 1}; const int MOD = 1e9 + 7; const double pi = acos(-1.0); const int MAXN = 50 + 10; const int MAXT = 10000 + 10; using namespace std; double a[MAXN], dp[MAXN][MAXN]; double solve(int l, int r){ if(dcmp(dp[l][r], -1)) return dp[l][r]; if(r - l == 1) return dp[l][r] = 0.0; double mi = 1e15; for(int k = l + 1; k < r; ++k){ double tmp = solve(l, k) + solve(k, r); if(dcmp(tmp, mi) == -1) mi = tmp; } return dp[l][r] = mi + a[r] - a[l]; } int main(){ double L; while(scanf("%lf", &L) == 1){ if(!dcmp(L, 0)) return 0; int n; scanf("%d", &n); a[0] = 0.0; for(int i = 1; i <= n; ++i){ scanf("%lf", &a[i]); } a[n + 1] = L; for(int i = 0; i <= n + 1; ++i) for(int j = 0; j <= n + 1; ++j) dp[i][j] = -1; printf("The minimum cutting is %g.\n", solve(0, n + 1)); } return 0; }