fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. int main() {
  5. int n;
  6. cin >> n;
  7.  
  8. vector<long long> a(n + 1), prefix(n + 1, 0);
  9.  
  10. for (int i = 1; i <= n; i++) {
  11. cin >> a[i];
  12. }
  13.  
  14. // Sort the array
  15. sort(a.begin() + 1, a.begin() + n + 1);
  16.  
  17. // Build prefix sum
  18. for (int i = 1; i <= n; i++) {
  19. prefix[i] = prefix[i - 1] + a[i];
  20. }
  21.  
  22. long long totalSum = prefix[n];
  23.  
  24. int q;
  25. cin >> q;
  26.  
  27. while (q--) {
  28. long long target;
  29. cin >> target;
  30.  
  31. // Binary search: last index with a[i] <= target
  32. int low = 1, high = n, g = 0;
  33.  
  34. while (low <= high) {
  35. int mid = low + (high - low) / 2;
  36. if (a[mid] <= target) {
  37. g = mid;
  38. low = mid + 1;
  39. } else {
  40. high = mid - 1;
  41. }
  42. }
  43.  
  44. // Left part cost
  45. long long left_cost = target * g - prefix[g];
  46.  
  47. // Right part cost
  48. long long right_cost =
  49. (totalSum - prefix[g]) - target * (n - g);
  50.  
  51. long long ans = left_cost + right_cost;
  52.  
  53. cout << ans << "\n";
  54. }
  55.  
  56. return 0;
  57. }
  58.  
Success #stdin #stdout 0.01s 5308KB
stdin
3
1 2 3
4
3 2 1 5
stdout
3
2
3
9