fork(1) download
  1. #include <bits/stdc++.h> // NeOWami
  2. using namespace std;
  3.  
  4. #define ft first
  5. #define sc second
  6. #define int long long
  7. using pii = pair<int, int>;
  8. template<class T> using heapmin = priority_queue<T, vector<T>, greater<T>>;
  9.  
  10. const int N = 3e5 + 5;
  11.  
  12. int n, k;
  13. int a[N];
  14. int val[N], L[N], R[N], curID;
  15. bool del[N];
  16. signed main() {
  17. cin.tie(NULL)->sync_with_stdio(false);
  18. if(ifstream("BACKUP.inp")) {
  19. freopen("BACKUP.inp", "r", stdin);
  20. freopen("BACKUP.out", "w", stdout);
  21. }
  22. cin >> n >> k;
  23. for (int i = 1; i <= n; i++) cin >> a[i];
  24. sort(a + 1, a + n + 1);
  25. heapmin<pii> pq;
  26. for (int i = 1; i < n; i++) {
  27. ++curID;
  28. val[i] = a[i + 1] - a[i];
  29. L[i] = i - 1;
  30. R[i] = (i + 1 == n) ? 0 : i + 1;
  31. pq.push({val[i], i});
  32. }
  33.  
  34. curID = n;
  35. int cnt = 0, ans = 0;
  36. while(cnt < k) {
  37. int i = pq.top().sc;
  38. pq.pop();
  39. if (del[i]) continue;
  40. ans += val[i];
  41. del[i] = 1;
  42. cnt++;
  43.  
  44. int l = L[i], r = R[i];
  45. del[l] = del[r] = 1;
  46.  
  47. int leftL = l ? L[l] : 0;
  48. int rightR = r ? R[r] : 0;
  49. if (l && r) {
  50. int id = ++curID;
  51. val[id] = val[l] + val[r] - val[i];
  52. L[id] = leftL, R[id] = rightR;
  53. if (leftL) R[leftL] = id;
  54. if (rightR) L[rightR] = id;
  55. del[id] = 0;
  56. pq.push({val[id], id});
  57. }
  58. else {
  59. if (leftL) R[leftL] = rightR;
  60. if (rightR) L[rightR] = leftL;
  61. }
  62. }
  63. cout << ans;
  64. return 0;
  65. }
Success #stdin #stdout 0.01s 5280KB
stdin
Standard input is empty
stdout
Standard output is empty