fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. #define int long long int
  4. #define double long double
  5. #define print(a) for(auto x : a) cout << x << " "; cout << endl
  6.  
  7.  
  8. const int M = 1000000007;
  9. const int N = 3e5+9;
  10. const int INF = 2e9+1;
  11. const int LINF = 2000000000000000001;
  12.  
  13. inline int power(int a, int b, int mod=M) {
  14. int x = 1;
  15. a %= mod;
  16. while (b) {
  17. if (b & 1) x = (x * a) % mod;
  18. a = (a * a) % mod;
  19. b >>= 1;
  20. }
  21. return x;
  22. }
  23.  
  24.  
  25. //_ ***************************** START Below *******************************
  26.  
  27.  
  28.  
  29.  
  30. vector<int> a;
  31.  
  32. //* Take every thing 1 based indexed (even prefix , except input a[ ] )
  33.  
  34. int consistency(int n, int k){
  35.  
  36. sort(begin(a), end(a));
  37.  
  38. vector<int> pf(n+1, 0);
  39. for(int i=0; i<n; i++){
  40. pf[i+1] = pf[i] + a[i];
  41. }
  42.  
  43. vector<vector<int>> dp(n+1, vector<int>(k+1, INF));
  44. dp[0][0] = 0;
  45.  
  46. for(int i=1; i<=n; i++){
  47. for(int x=1; x<=k; x++){
  48.  
  49. int j = i-1;
  50. while(j>=0){
  51.  
  52. int mid = (i+j)/2 + 1;
  53.  
  54. int leftCost = (mid-j)*a[mid-1] - (pf[mid] - pf[j]);
  55. int rightCost = (pf[i]-pf[mid]) - (i-mid)*a[mid-1];
  56.  
  57. dp[i][x] = min(dp[i][x], dp[j][x-1] + leftCost + rightCost );
  58.  
  59. j--;
  60. }
  61. }
  62. }
  63.  
  64. return dp[n][k];
  65. }
  66.  
  67.  
  68.  
  69.  
  70.  
  71.  
  72.  
  73.  
  74.  
  75.  
  76.  
  77.  
  78.  
  79.  
  80.  
  81. int practice(int n, int k){
  82.  
  83.  
  84. return 0;
  85. }
  86.  
  87.  
  88.  
  89.  
  90.  
  91. void solve() {
  92.  
  93. int n, k;
  94. cin>> n >> k;
  95.  
  96. a.resize(n);
  97. for(int i=0; i<n; i++) cin >> a[i];
  98.  
  99. cout << consistency(n, k) << endl;
  100.  
  101.  
  102. }
  103.  
  104.  
  105.  
  106.  
  107.  
  108. int32_t main() {
  109. ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
  110.  
  111. int t = 1;
  112. // cin >> t;
  113. while (t--) {
  114. solve();
  115. }
  116.  
  117. return 0;
  118. }
Success #stdin #stdout 0.01s 5280KB
stdin
5 3
1 4 8 10 20
stdout
5