fork download
  1. #include <iostream>
  2. #include <vector>
  3. #include <numeric>
  4. #include <algorithm>
  5. using namespace std;
  6.  
  7. // 0-based indexing
  8. int main() {
  9. int n;
  10. cin >> n;
  11. vector<int> arr(n);
  12. for (int i = 0; i < n; i++) cin >> arr[i];
  13.  
  14. int target;
  15. cin >> target;
  16.  
  17. int total = accumulate(arr.begin(), arr.end(), 0);
  18. sort(arr.begin(), arr.end());
  19.  
  20. int leftInd = distance(arr.begin(), lower_bound(arr.begin(), arr.end(), target));
  21.  
  22. int sumOfLeftPart = 0;
  23. for (int i = 0; i < leftInd; i++) {
  24. sumOfLeftPart += arr[i];
  25. }
  26.  
  27. int leftCount = leftInd;
  28. int leftSum = target * leftCount - sumOfLeftPart;
  29.  
  30. int sumOfRightPart = total - sumOfLeftPart;
  31. int rightCount = n - leftCount;
  32. int rightSum = sumOfRightPart - target * rightCount;
  33.  
  34. cout << leftSum + rightSum << "\n";
  35. return 0;
  36. }
  37.  
Success #stdin #stdout 0.01s 5308KB
stdin
5
1 2 3 10 12
5
stdout
21