tuki2501

LARMY.cpp

Nov 10th, 2021 (edited)
429
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.31 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. const int N = 5005;
  5.  
  6. int n, k;
  7. int a[N], cost[N][N];
  8. int dp[N][N], opt[N][N];
  9.  
  10. template<typename T>
  11. bool chmin(T &a, T b) {
  12.   return a > b ? a = b, 1 : 0;
  13. }
  14.  
  15. void compute(int k, int l, int r, int optl, int optr) {
  16.   if (l > r) return;
  17.   int m = (l + r) / 2, opt = optl;
  18.   for (int i = optl; i <= min(optr, m); i++) {
  19.     if (chmin(dp[k][m], dp[k - 1][i - 1] + cost[m][m] - cost[m][i - 1])) {
  20.       opt = i;
  21.     }
  22.   }
  23.   compute(k, l, m - 1, optl, opt);
  24.   compute(k, m + 1, r, opt, optr);
  25. }
  26.  
  27. int main() {
  28.   cin.tie(0)->sync_with_stdio(0);
  29.   cin >> n >> k;
  30.   for (int i = 1; i <= n; i++) {
  31.     cin >> a[i];
  32.   }
  33.   for (int i = 1; i <= n; i++) {
  34.     for (int j = 1; j <= n; j++) {
  35.       cost[i][j] = cost[i][j - 1];
  36.       if (a[j] > a[i] && j < i) cost[i][j]++;
  37.     }
  38.     for (int j = 1; j <= n; j++) {
  39.       cost[i][j] += cost[i - 1][j];
  40.     }
  41.   }
  42.   memset(dp, 0x3f, sizeof(dp)); dp[0][0] = 0;
  43. //  for (int k = 1; k <= n; k++) {
  44. //    for (int i = 1; i <= n; i++) {
  45. //      for (int j = 1; j <= i; j++) {
  46. //        if (chmin(dp[k][i], dp[k - 1][j - 1] + cost[i][i] - cost[i][j - 1])) {
  47. //          opt[k][i] = j;
  48. //        }
  49. //      }
  50. //    }
  51. //  }
  52.   for (int k = 1; k <= n; k++) {
  53.     compute(k, 1, n, 1, n);
  54.   }
  55.   cout << dp[k][n] << '\n';
  56. }
Add Comment
Please, Sign In to add comment