fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. int left_part_last_index(long long target, const vector<long long>& arr, int n) {
  5. int low = 1; // Start at 1 to skip arr[0] sentinel
  6. int high = n; // End at n to skip arr[n+1] sentinel
  7. int answer = 0; // Initialize default value (0 elements <= target)
  8.  
  9. while(low <= high) {
  10. int mid = low + (high - low) / 2; // Fixed precedence bug: (low + high) / 2
  11.  
  12. if(arr[mid] <= target) {
  13. answer = mid; // Store valid candidate index
  14. low = mid + 1; // Look for a larger valid index on the right
  15. } else {
  16. high = mid - 1; // Element too large, search left
  17. }
  18. }
  19. return answer;
  20. }
  21.  
  22. int main() {
  23. int n;
  24. if (!(cin >> n)) return 0;
  25.  
  26. // arr size is n+2 to safely hold INT_MIN at 0 and INT_MAX at n+1
  27. vector<long long> arr(n+2);
  28. vector<long long> prefix(n+1, 0); // Changed to long long to prevent overflow
  29.  
  30. // Fixed: Store elements from index 1 to n (leaving 0 and n+1 for sentinels)
  31. for(int i = 1; i <= n; i++) {
  32. cin >> arr[i];
  33. }
  34.  
  35. // Fixed: Set sentinels AFTER taking inputs so they aren't overwritten
  36. arr[0] = LLONG_MIN;
  37. arr[n+1] = LLONG_MAX;
  38.  
  39. // Fixed: Sort ONLY the elements from index 1 to n
  40. sort(arr.begin() + 1, arr.begin() + n + 1);
  41.  
  42. // Fixed: Compute prefix sums AFTER sorting (and correctly handling prefix[0] = 0)
  43. long long sum = 0;
  44. for(int i = 1; i <= n; i++) {
  45. sum += arr[i];
  46. prefix[i] = prefix[i-1] + arr[i]; // No more negative indexing (prefix[0] exists)
  47. }
  48.  
  49. int q;
  50. cin >> q;
  51.  
  52. for(int i = 0; i < q; i++) {
  53. long long target;
  54. cin >> target;
  55.  
  56. // li represents the number of elements <= target (from index 1 to li)
  57. long long li = left_part_last_index(target, arr, n);
  58.  
  59. long long left_part = target * li - (prefix[li]); // O(1)
  60. long long right_part = (sum - prefix[li]) - target * (n - li); // O(1)
  61.  
  62. long long min_operations = left_part + right_part;
  63.  
  64. cout << "Minimum operations for target " << target << " is : " << min_operations << endl;
  65. }
  66. return 0;
  67. }
Success #stdin #stdout 0.01s 5316KB
stdin
5
1
2
3
4
5
2
2
8
stdout
Minimum operations for target 2 is : 7
Minimum operations for target 8 is : 25