fork download
  1. import java.util.*;
  2.  
  3. public class Main {
  4.  
  5. public static int findPosition(ArrayList<Long> list, long target) {
  6. int index = Collections.binarySearch(list, target);
  7. return index >= 0 ? index : -index - 1;
  8. }
  9.  
  10. public static void main(String[] args) {
  11. Scanner sc = new Scanner(System.in);
  12. int n = sc.nextInt();
  13.  
  14. ArrayList<Long> numbers = new ArrayList<>();
  15. long[] prefixSum = new long[n + 1];
  16. long totalSum = 0;
  17.  
  18. for (int i = 0; i < n; i++) {
  19. long num = sc.nextLong();
  20. numbers.add(num);
  21. totalSum += num;
  22. }
  23.  
  24. Collections.sort(numbers);
  25.  
  26. for (int i = 1; i <= n; i++) {
  27. prefixSum[i] = prefixSum[i - 1] + numbers.get(i - 1);
  28. }
  29.  
  30. int queries = sc.nextInt();
  31. while (queries-- > 0) {
  32. long target = sc.nextLong();
  33. int pos = findPosition(numbers, target);
  34.  
  35. long leftSum = target * pos - prefixSum[pos];
  36. long rightSum = (totalSum - prefixSum[pos]) - target * (n - pos);
  37.  
  38. System.out.println(leftSum + rightSum);
  39. }
  40. }
  41. }
  42.  
Success #stdin #stdout 0.13s 56536KB
stdin
7 
5 6 7 8 3 8 9
3
3
4
5
stdout
25
20
15