|
| 1 | +// Question CODE: Minimum Cost to Cut a Stick |
| 2 | +/* Question: Given a wooden stick of length n units. The stick is labelled from 0 to n. |
| 3 | + Given an integer array cuts where cuts[i] denotes a position you should perform a cut at. |
| 4 | + You should perform the cuts in order, you can change the order of the cuts as you wish. |
| 5 | + The cost of one cut is the length of the stick to be cut, the total cost is the sum of costs of all cuts. When you cut a stick, |
| 6 | + it will be split into two smaller sticks (i.e. the sum of their lengths is the length of the stick before the cut). |
| 7 | + Return the minimum total cost of the cuts.*/ |
| 8 | +/* Input: |
| 9 | + Input contains number of testcases, size of a vector n and a vector for each testcase |
| 10 | + Sample Input 1: |
| 11 | + 1 |
| 12 | + 7 |
| 13 | + 1 3 4 5 |
| 14 | +*/ |
| 15 | +/* Output: |
| 16 | +The only line of the output prints the minimum total cost of the cuts. |
| 17 | +Sample Output 1: |
| 18 | +16 |
| 19 | +Explanation Of Sample Input 1: |
| 20 | +Rearranging the cuts to be [3, 5, 1, 4] for example will lead to a scenario with total cost = 16 (7 + 4 + 3 + 2 = 16). |
| 21 | + |
| 22 | +*/ |
| 23 | + |
| 24 | + |
| 25 | + |
| 26 | +#include <bits/stdc++.h> |
| 27 | +using namespace std; |
| 28 | + |
| 29 | +int dp[102][102] = {}; |
| 30 | +int dfs(vector<int>& cuts, int i, int j) |
| 31 | +{ |
| 32 | + if (j - i <= 1) |
| 33 | + return 0; |
| 34 | + if (!dp[i][j]) |
| 35 | + { |
| 36 | + dp[i][j] = INT_MAX; |
| 37 | + for (auto k = i + 1; k < j; ++k) |
| 38 | + dp[i][j] = min(dp[i][j], cuts[j] - cuts[i] + dfs(cuts, i, k) + dfs(cuts, k, j)); |
| 39 | + } |
| 40 | + return dp[i][j]; |
| 41 | +} |
| 42 | +int minCost(int n, vector<int>& cuts) |
| 43 | +{ |
| 44 | + cuts.push_back(0); |
| 45 | + cuts.push_back(n); |
| 46 | + sort(begin(cuts), end(cuts)); |
| 47 | + return dfs(cuts, 0, cuts.size() - 1); |
| 48 | +} |
| 49 | +int main() |
| 50 | +{ |
| 51 | + #ifndef ONLINE_JUDGE |
| 52 | + freopen("input.txt", "r", stdin); |
| 53 | + freopen("output.txt", "w", stdout); |
| 54 | + #endif |
| 55 | + int tc; |
| 56 | + cin>>tc; |
| 57 | + while(tc--) |
| 58 | + { |
| 59 | + int n; |
| 60 | + cin>>n; |
| 61 | + vector<int> vec(n); |
| 62 | + for(int i=0;i<n;i++) |
| 63 | + { |
| 64 | + cin>>vec[i]; |
| 65 | + } |
| 66 | + cout<<minCost(n,vec)<<endl; |
| 67 | + } |
| 68 | + |
| 69 | + return 0; |
| 70 | +} |
0 commit comments