fork download
  1. #include <iostream>
  2. #include <vector>
  3. #include <algorithm>
  4.  
  5. using namespace std;
  6.  
  7. const long long INF = 1e18;
  8.  
  9. long long solve(int N, int K, int L, int R, vector<int>& a) {
  10. // dp[i][j] = min cost to partition first i elements into j groups
  11. vector<vector<long long>> dp(N + 1, vector<long long>(K + 1, INF));
  12.  
  13. dp[0][0] = 0;
  14.  
  15. for (int j = 1; j <= K; ++j) {
  16. for (int i = 1; i <= N; ++i) {
  17. int current_max = -1e9 - 7;
  18. int current_min = 1e9 + 7;
  19.  
  20. // Try all possible lengths for the j-th group ending at i
  21. // The group starts at index i - len and ends at i - 1
  22. for (int len = 1; len <= min(i, R); ++len) {
  23. int val = a[i - len];
  24. current_max = max(current_max, val);
  25. current_min = min(current_min, val);
  26.  
  27. if (len >= L && dp[i - len][j - 1] != INF) {
  28. dp[i][j] = min(dp[i][j], dp[i - len][j - 1] + (current_max - current_min));
  29. }
  30. }
  31. }
  32. }
  33.  
  34. return dp[N][K];
  35. }
  36.  
  37. int main() {
  38. ios_base::sync_with_stdio(false);
  39. cin.tie(NULL);
  40.  
  41. int N, K, L, R;
  42. if (!(cin >> N >> K >> L >> R)) return 0;
  43.  
  44. vector<int> a(N);
  45. for (int i = 0; i < N; ++i) {
  46. cin >> a[i];
  47. }
  48.  
  49. cout << solve(N, K, L, R, a) << endl;
  50.  
  51. return 0;
  52. }
Success #stdin #stdout 0s 5320KB
stdin
5
2
2
3
10 1 5 20 2
stdout
27