Advertisement
VladNitu

Untitled

Dec 10th, 2022
41
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.44 KB | None | 0 0
  1. //Greedy prost
  2. #define NMAX 2023
  3. #define ui unsigned int
  4. #define ll long long
  5. #define MOD (int)(1e9 + 7)
  6.  
  7. #include <bits/stdc++.h>
  8.  
  9. using namespace std;
  10.  
  11. int N, Max = INT_MIN, Min = INT_MAX;
  12. vector<int> v;
  13. ll ans = 0;
  14. void solve(int mid) {
  15. int l = mid - 1;
  16. int r = mid + 1;
  17. Max = v[mid];
  18. Min = v[mid];
  19.  
  20. while (l >= 0 && r < N)
  21. {
  22. int diffLeft = Max - v[l];
  23. int diffRight = v[r] - Min;
  24. if (diffLeft < diffRight)
  25. {
  26. ans += diffLeft;
  27. Min = v[l];
  28. l --;
  29. }
  30. else {
  31. ans += diffRight;
  32. Max = v[r];
  33. r ++;
  34. }
  35. }
  36.  
  37. while (l >= 0){
  38. ans += (Max - v[l]);
  39. l--;
  40. }
  41. while (r < N) {
  42. ans += v[r] - Min;
  43. r ++;
  44. }
  45.  
  46.  
  47. }
  48.  
  49. int main() {
  50. cin >> N;
  51. v = vector<int>(N);
  52. for (int i = 0; i < N; ++i)
  53. cin >> v[i];
  54.  
  55. sort(v.begin(), v.end());
  56.  
  57. if (N == 1) {
  58. cout << 0;
  59. return 0;
  60. }
  61. if (N == 2) {
  62. return max(v[0], v[1]) - min(v[0], v[1]);
  63. }
  64.  
  65.  
  66. int mid = N / 2;
  67. if (N % 2 != 0)
  68. {
  69. solve(mid);
  70. cout << ans << '\n';
  71. }
  72. else {
  73. solve(mid);
  74. ll sol1 = ans;
  75. ans = 0;
  76. solve(mid - 1);
  77. ll sol2 = ans;
  78. // cout << sol1 << ' ' << sol2 << '\n';
  79. cout << min(sol1, sol2);
  80. }
  81.  
  82. return 0;
  83. }
  84.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement