fork download
  1. import java.util.*;
  2. import java.lang.*;
  3. import java.io.*;
  4.  
  5. class Ideone {
  6. public static void main (String[] args) throws java.lang.Exception {
  7. Scanner in = new Scanner(System.in);
  8. int n = in.nextInt();
  9. int q = in.nextInt();
  10.  
  11. long b[] = new long[n+1];
  12. long query[][] = new long[q+1][3];
  13. long t = 0;
  14.  
  15. for(int i=1;i<=n;i++){
  16. b[i] = in.nextLong();
  17. t = t + b[i];
  18. }
  19. for(int j=1;j<=q;j++){
  20. query[j][1] = in.nextLong();
  21. query[j][2] = in.nextLong();
  22. }
  23.  
  24. for(int i=1;i<=q;i++){
  25. long x1 = query[i][1];
  26. long y1 = query[i][2];
  27. long cost = (long)1e18;
  28.  
  29. for(int j=1;j<=n;j++){
  30. long c1 = 0, c2 = 0;
  31. if(b[j] < x1){
  32. c1 += (x1 - b[j]);
  33. }
  34. long remaining_sum = t - b[j];
  35. if(remaining_sum < y1){
  36. c2 += (y1 - remaining_sum);
  37. }
  38. cost = Math.min(cost, c1 + c2);
  39. }
  40.  
  41. System.out.println(cost);
  42. }
  43. }
  44. }
  45.  
Success #stdin #stdout 0.11s 56636KB
stdin
3 2
2 5 4
4 7
10 10
stdout
0
9