fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6.  
  7. /* Name of the class has to be "Main" only if the class is public. */
  8. class Ideone
  9. {
  10. public static void main (String[] args) throws java.lang.Exception
  11. {
  12. // your code goes here
  13. Scanner sc=new Scanner(System.in);
  14. int n=sc.nextInt();
  15.  
  16. ArrayList<Long> arr=new ArrayList<>();
  17. arr.add((long)-1e18);
  18. long [] prefix=new long [n+1];
  19. long sum=0;
  20.  
  21. for(int i=1;i<=n;i++){
  22. long num=sc.nextLong();
  23. arr.add(num);
  24. sum+=num;
  25. }
  26.  
  27. arr.add((long)1e18);
  28. Collections.sort(arr.subList(1,n+1));
  29. for(int i=1;i<=n;i++){
  30. prefix[i]=arr.get(i)+ prefix[i-1];
  31. }
  32. int q=sc.nextInt();
  33. while(q-->0){
  34. long target=sc.nextLong();
  35. int idx=lower(arr,target);
  36. long leftPart=target*idx-prefix[idx];
  37. long rightPart=sum-prefix[idx]-target*(n-idx);
  38. System.out.println(leftPart+rightPart);
  39. }
  40.  
  41. sc.close();
  42. }
  43. public static int lower(ArrayList<Long>arr,long target){
  44. int idx=Collections.binarySearch(arr,target);
  45. if(idx<0){
  46. idx=-idx-1;
  47. }else{
  48. idx++;
  49. }
  50. return idx-1;
  51. }
  52. }
Success #stdin #stdout 0.13s 56652KB
stdin
5
1 2 3 4 5
2
2 3
stdout
7
6