Fastrail08

LC: 1547 Minimum Cost To Cut Stick

Sep 13th, 2025
145
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.32 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4.  
  5. int minimumCost(int i, int j, vector<int> &paddedCuts, vector<vector<int> > &memo){
  6.     // cout << i << " " << j << '\n';
  7.     //no cuts available, so the cost of not cutting the stick is 0
  8.     if(j - i <= 1){
  9.         return 0;
  10.     }
  11.    
  12.     if(memo[i][j] != -1){
  13.         return memo[i][j];
  14.     }
  15.    
  16.     int minIJ = INT_MAX;
  17.     for(int k = i + 1; k < j; k++){
  18.         int cutPosition = paddedCuts[k];
  19.        
  20.         int leftCost = minimumCost(i, k, paddedCuts, memo);
  21.         int rightCost = minimumCost(k, j, paddedCuts, memo);
  22.         minIJ = min(minIJ, leftCost + (paddedCuts[j] - paddedCuts[i]) + rightCost);
  23.     }
  24.     return memo[i][j] = minIJ;
  25.  }
  26.  
  27.  
  28. int minCuts(int length, vector<int> &cuts){
  29.     sort(cuts.begin(), cuts.end());
  30.    
  31.     vector<int> paddedCuts;
  32.     paddedCuts.push_back(0);
  33.     paddedCuts.insert(paddedCuts.end(), cuts.begin(), cuts.end());
  34.     paddedCuts.push_back(length);
  35.    
  36.     int n = paddedCuts.size();
  37.     vector<vector<int> > memo(n, vector<int>(n, -1));
  38.     return minimumCost(0, n - 1, paddedCuts, memo);
  39. }
  40.  
  41. int main() {
  42.     // your code goes here
  43.     int n, k;
  44.     cin >> n >> k;
  45.     vector<int> cuts(k);
  46.     for(int i = 0; i < k; i++){
  47.         cin >> cuts[i];
  48.     }
  49.    
  50.     cout << minCuts(n, cuts) << '\n';
  51. }
  52.  
Advertisement
Add Comment
Please, Sign In to add comment