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> b;
  31.  
  32. int consistency(int n, int k){
  33.  
  34. sort(begin(b), end(b));
  35.  
  36. n = b.size();
  37. vector<int> prefix(n+1);
  38. vector<int> suffix(n+1);
  39.  
  40.  
  41. for(int i=0; i<n; i++){
  42. prefix[i+1] = prefix[i] + b[i];
  43. }
  44. for(int i=n-1; i>=0; i--){
  45. suffix[i] = suffix[i+1] + b[i];
  46. }
  47.  
  48. int ans = INT32_MAX;
  49. for(int i=0; i<n; i++){
  50.  
  51. int j = i;
  52. while(j<n && b[j] - b[i] <= k) j++;
  53.  
  54. int cost = prefix[i] + suffix[j] - (n-j)*(b[i]+k);
  55. ans = min(ans, cost);
  56. }
  57.  
  58. return ans;
  59.  
  60. }
  61.  
  62.  
  63.  
  64.  
  65.  
  66.  
  67.  
  68.  
  69.  
  70.  
  71.  
  72.  
  73.  
  74.  
  75.  
  76. int practice(int n, int k){
  77.  
  78.  
  79. return 0;
  80. }
  81.  
  82.  
  83.  
  84.  
  85.  
  86. void solve() {
  87.  
  88. int n, k;
  89. cin>> n >> k;
  90.  
  91. b.resize(n);
  92. for(int i=0; i<n; i++) cin >> b[i];
  93.  
  94. cout << consistency(n, k) << endl;
  95.  
  96.  
  97. }
  98.  
  99.  
  100.  
  101.  
  102.  
  103. int32_t main() {
  104. ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
  105.  
  106. int t = 1;
  107. cin >> t;
  108. while (t--) {
  109. solve();
  110. }
  111.  
  112. return 0;
  113. }
Success #stdin #stdout 0s 5324KB
stdin
2
5 10
5 10 15 20 25
5 15
5 10 15 20 25
stdout
10
5