fork download
  1. import java.io.*;
  2. import java.util.*;
  3.  
  4. class Ideone {
  5. static class Fast {
  6.  
  7. Fast() throws IOException {
  8. st = new StringTokenizer(br.readLine());
  9.  
  10. }
  11.  
  12. String next() throws IOException {
  13. return (st.hasMoreElements() ? st.nextToken() : (st = new StringTokenizer(br.readLine())).nextToken());
  14. }
  15.  
  16. int nextInt() throws IOException {
  17. return Integer.parseInt(next());
  18. }
  19.  
  20. long nextLong() throws IOException {
  21. return Long.parseLong(next());
  22. }
  23.  
  24. void print(Object o) throws IOException {
  25. String s = String.valueOf(o);
  26. bw.write(s);
  27. bw.flush();
  28. }
  29. }
  30.  
  31. public static void main(String args[]) throws IOException {
  32. Fast f = new Fast();
  33. int t = f.nextInt();
  34. while (t-- != 0) {
  35.  
  36. int n = f.nextInt();
  37. HashMap<Integer, Integer> map = new HashMap<>();
  38. for (int i = 0; i < n; i++) {
  39. int x = f.nextInt();
  40. map.put(x, map.containsKey(x) ? map.get(x) + 1 : 1);
  41. int y = f.nextInt();
  42. map.put(y + 1, map.containsKey(y + 1) ? map.get(y + 1) - 1 : -1);
  43. }
  44. // created an map of l and r+1 with respective values . . . .
  45.  
  46. int q = f.nextInt();
  47. //input queries
  48. int qr[] = new int[q];
  49. for (int i = 0; i < q; i++) {
  50. qr[i] = f.nextInt();
  51. }
  52.  
  53. //to check the missing values in between an arraylist
  54. ArrayList<Integer> list = new ArrayList<>(map.keySet());
  55. int max = list.get(list.size() - 1);
  56. int min = list.get(0);
  57. int sum = 0;
  58. //to create a prefix map sortof thing
  59. for (Map.Entry<Integer, Integer> entry : map.entrySet())
  60. {
  61. sum += entry.getValue();
  62. entry.setValue(sum);
  63. }
  64.  
  65. for (int i = 0; i < q; i++) {
  66. //every query in q[] if is >=min of arraylist and <=max of arraylist
  67. if (qr[i] <= max && qr[i]>=min ) {
  68. if (list.contains(qr[i])) {
  69. f.print(map.get(qr[i]) + "\n"); //if we have it in the list we will print its corresponding value else we'll have to search for its corresponding value in prefix map which is just less than it
  70. } else {
  71. int start = 0;
  72. int end = list.size() - 1;
  73. int ans = -1;
  74. while (start <= end) {
  75. int mid = (start + end) / 2;
  76. if (list.get(mid) >= qr[i]) {
  77. end = mid - 1;
  78. } else {
  79. ans = mid;
  80. start = mid + 1;
  81. }
  82. }
  83. f.print(map.get(list.get(ans)) + "\n");
  84. }
  85. }
  86. else{ //if value is outside the range of min and max // not produced by manufactures
  87. f.print(0 + "\n");
  88. }
  89. }
  90. }
  91. }
  92.  
  93. }
Success #stdin #stdout 0.13s 52376KB
stdin
1
4
1 3
1 6
3 5
5 9
4
3
8
6
10
stdout
3
1
2
0