Guest User

DQUERY Java

a guest
Mar 21st, 2020
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.28 KB | None | 0 0
  1. import java.io.*;
  2. import java.util.*;
  3.  
  4. class Pair<T, U, V>
  5. {
  6. T f;
  7. U s;
  8. V i;
  9. public Pair(T Integer1, U Integer2, V i)
  10. {
  11. f=Integer1; s=Integer2;this.i=i;
  12. }
  13. T first()
  14. {
  15. return f;
  16. }
  17. U second()
  18. {
  19. return s;
  20. }
  21. V geti()
  22. {
  23. return i;
  24. }
  25. }
  26.  
  27. class Main
  28. {
  29. static int[] a, counter, ans;
  30. static long[][] dpS, dpN, dp;
  31. static int n, count;
  32. static int BLOCK;
  33.  
  34. static void add(int index)
  35. {
  36. if(counter[a[index]] == 0)
  37. count++;
  38. }
  39.  
  40. static void remove(int index)
  41. {
  42. if(counter[a[index]] == 1)
  43. count--;
  44. }
  45.  
  46. public static void main(String[] args) throws Exception
  47. {
  48. Scanner sc= new Scanner(System.in);
  49.  
  50. int n= sc.nextInt();
  51. Main.n =n;
  52. BLOCK=(int)Math.sqrt(n);
  53. a= new int[n+2];
  54. for(int i=1; i<=n; i++)
  55. {
  56. a[i]= sc.nextInt();
  57. }
  58. int q= sc.nextInt();
  59. ans= new int[q];
  60.  
  61. List<Pair<Integer, Integer, Integer>> list= new ArrayList<Pair<Integer, Integer, Integer>>();
  62. for(int k=0; k<q; k++)
  63. {
  64. list.add(new Pair<Integer, Integer, Integer>(sc.nextInt(), sc.nextInt(),k));
  65. }
  66.  
  67. list.sort(new Comparator<Pair<Integer, Integer, Integer>>() {
  68. @Override
  69. public int compare(Pair<Integer, Integer, Integer> o1, Pair<Integer, Integer, Integer> o2) {
  70. if (o1.first()/BLOCK > o2.first()/BLOCK)
  71. {
  72. return 1;
  73. }
  74. else if ((o1.first()/BLOCK) == (o2.first()/BLOCK))
  75. {
  76. if(o1.second() > o2.second())
  77. return 1;
  78. else
  79. return -1;
  80. }
  81. else
  82. {
  83. return -1;
  84. }
  85. }
  86. });
  87.  
  88. counter= new int[3000000];
  89. int currentL=1, currentR=1;
  90. for(int m=0;m<q;m++)
  91. {
  92. while(currentL < list.get(m).first())
  93. {
  94. remove(currentL);
  95. counter[a[currentL]]--;
  96. currentL++;
  97. }
  98. while(currentL >= list.get(m).first())
  99. {
  100. add(currentL);
  101. counter[a[currentL]]++;
  102. currentL--;
  103. }
  104. while(currentR > list.get(m).second())
  105. {
  106. remove(currentR);
  107. counter[a[currentR]]--;
  108. currentR--;
  109. }
  110. while(currentR <= list.get(m).second())
  111. {
  112. add(currentR);
  113. counter[a[currentR]]++;
  114. currentR++;
  115. }
  116.  
  117. ans[list.get(m).geti()]= count;
  118. }
  119.  
  120. for(int m=0;m<q;m++)
  121. {
  122. System.out.println(ans[m]);
  123. }
  124. }
  125.  
  126. }
Add Comment
Please, Sign In to add comment