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 int bs(int arr[],int target){
  11. int low = 0;
  12. int high = arr.length-1;
  13. int idx = arr.length;
  14. while(low<=high){
  15. int mid = low+(high-low)/2;
  16. if(target<=arr[mid]){
  17. high=mid-1;
  18. idx = mid;
  19. }else low = mid+1;
  20. }
  21. return idx;
  22. }
  23. public static void main (String[] args) throws java.lang.Exception
  24. {
  25. // your code goes here
  26. Scanner sc = new Scanner(System.in);
  27. int n = sc.nextInt();
  28. int q = sc.nextInt();
  29.  
  30. int arr[] = new int[n];
  31. for(int i=0;i<n;i++) arr[i] = sc.nextInt();
  32.  
  33. int targets[] = new int[q];
  34. for(int i=0;i<q;i++) targets[i] = sc.nextInt();
  35.  
  36. Arrays.sort(arr);
  37.  
  38. int preq[] = new int[n+1];
  39. for(int i=1;i<=n;i++){
  40. preq[i] = preq[i-1]+arr[i-1];
  41. }
  42. int totSum = preq[n];
  43. List<Integer>li = new ArrayList<>();
  44. for(int i=0;i<q;i++){
  45. int idx = bs(arr,targets[i]);
  46. int leftHalf = targets[i]*idx-preq[idx];
  47. int rightHalf = totSum-preq[idx]-targets[i]*(n-idx);
  48. li.add(leftHalf+rightHalf);
  49. }
  50. System.out.println(li);
  51. }
  52. }
Success #stdin #stdout 0.13s 56472KB
stdin
3 4
1 2 3
3 2 1 5
stdout
[3, 2, 3, 9]