Advertisement
7oSkaaa

Make It Equal

Aug 10th, 2021
106
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.99 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. #define cin(vec) for(auto& i : vec) cin >> i
  5. #define cin_2d(vec, n, m) for(int i = 0; i < n; i++) for(int j = 0; j < m && cin >> vec[i][j]; j++);
  6. #define cout(vec) for(auto& i : vec) cout << i << " "; cout << "\n";
  7. #define cout_2d(vec, n, m) for(int i = 0; i < n; i++, cout << "\n") for(int j = 0; j < m && cout << vec[i][j] << " "; j++);
  8. #define cout_map(mp) for(auto& [f, s] : mp) cout << f << "  " << s << "\n";
  9. #define Time cerr << "Time Taken: " << (float)clock() / CLOCKS_PER_SEC << " Secs" << "\n";
  10. #define fixed(n) cout << fixed << setprecision(n)
  11. #define ceil(n, m) (((n) / (m)) + ((n) % (m) ? 1 : 0))
  12. #define fill(vec, value) memset(vec, value, sizeof(vec));
  13. #define Num_of_Digits(n) ((int)log10(n)+1)
  14. #define all(vec) vec.begin(),vec.end()
  15. #define rall(vec) vec.rbegin(),vec.rend()
  16. #define sz(x) int(x.size())
  17. #define TC int t; cin >> t;   while(t--)
  18. #define fi first
  19. #define se second
  20. #define Pair pair < int, int >
  21. #define ll long long
  22. #define ull unsigned long long
  23. #define Mod  1'000'000'007
  24. #define INF 2'000'000'000
  25. #define EPS 1e-9
  26. #define PI acos(-1)
  27.  
  28. void Code_Crush(){
  29.   ios_base::sync_with_stdio(false), cin.tie(nullptr), cout.tie(nullptr);
  30.   #ifndef ONLINE_JUDGE
  31.     freopen("input.txt", "r", stdin), freopen("output.txt", "w", stdout);
  32.   #endif
  33. }
  34.  
  35. vector < int > nums;
  36.  
  37. ll F(int x){
  38.   ll moves = 0;
  39.   for(auto& i : nums)
  40.     moves += abs(i - x);
  41.   return moves;
  42. }
  43.  
  44. ll ternary_search(int l, int r){
  45.   while(r - l > 3){
  46.     int g = l + (r - l) / 3, h = r - (r - l) / 3;
  47.     if(F(g) == F(h)) l = g, r = h;
  48.     else (F(g) < F(h) ? r = h : l = g);
  49.   }
  50.   ll ans = F(l++);
  51.   for(int i = l; i <= r; i++)
  52.     ans = min(ans, F(i));
  53.   return ans;
  54. }
  55.  
  56. int main(){
  57.   Code_Crush();
  58.   freopen("equal.in", "r", stdin);
  59.   TC {
  60.     int n, l, r;                                cin >> n >> l >> r;
  61.     nums.resize(n);
  62.     cin(nums);
  63.     sort(all(nums));
  64.     cout << ternary_search(l, r) << "\n";  
  65.   }
  66.   Time
  67.   return 0;
  68. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement