给定长度为L的杆,任务是将杆切割,以使长度p,q和r的段总数最大。段只能是长度p,q和r
如果l = 15,p = 2,q = 3,r = 5,那么我们可以划分出7个段,如下所示:
{2, 2, 2, 2, 2, 2, 3}
我们可以使用动态编程解决这个问题
1. Initialize dp[] array to 0 2. Iterate till the length of the rod. For every i, a cut of p, q and r if possible is done. 3. Initialize ans[i+p] = max( ans[i+p], 1 + ans[i]), ans[i+q] = max(ans[i+q], 1 + ans[i]) and ans[i+r] = max(ans[i+r], 1 + ans[i]) for all the possible cuts. 4. ans[i] will be 0 if a cut at i-th index is not possible. ans[l] will give the maximum number of cuts possible
#include <bits/stdc++.h> using namespace std; int getMaximumSegments(int l, int p, int q, int r){ int dp[l + 1]; memset(dp, -1, sizeof(dp)); dp[0] = 0; for (int i = 0; i <= l; ++i) { if (dp[i] == -1) { continue; } if (i + p <= l) { dp[i + p] = max(dp[i + p], dp[i] + 1); } if (i + q <= l) { dp[i + q] = max(dp[i + q], dp[i] + 1); } if (i + r <= l) { dp[i + r] = max(dp[i + r], dp[i] + 1); } } return dp[l]; } int main(){ int l = 15, p = 2, q = 3, r = 5; cout << "Number of segments = " << getMaximumSegments(l, p, q, r) << endl; return 0; }
输出结果
当您编译并执行上述程序时。它生成以下输出-
Number of segments = 7