fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. int main()
  5. {
  6. int n;
  7. cin >> n;
  8. vector<int> costs(n);
  9. for(int &x : costs)
  10. cin >> x;
  11. int weeks;
  12. cin >> weeks;
  13.  
  14. vector<vector<int>> dp(n+1,vector<int>(weeks + 1, 1e9));
  15. //dp[i][w] - min cost to partition first i costs in w weeks
  16.  
  17. dp[0][0] = 0; //base case
  18.  
  19. for(int w = 1 ; w <= weeks ; w++)
  20. {
  21. for(int i = w ; i <= n ; i++)
  22. {
  23. int mx = 0; //cost for thsi partition
  24. for(int j = i - 1 ; j >= w - 1 ; j--)
  25. {
  26. mx = max(mx,costs[j]);
  27.  
  28. dp[i][w] = min(dp[i][w],
  29. dp[j][w-1] + mx);
  30. }
  31. }
  32. }
  33. cout << dp[n][weeks] << "\n";
  34.  
  35. return 0;
  36. }
Success #stdin #stdout 0.01s 5320KB
stdin
8
2 5 4 3 7 1 6 8
3
stdout
15