Advertisement
Guest User

Untitled

a guest
Feb 25th, 2018
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.05 KB | None | 0 0
  1. #!/bin/python3
  2.  
  3. import os
  4. import sys
  5. import math
  6. import bisect
  7. from collections import defaultdict
  8.  
  9. t = []
  10. query_solutions = [0]*1000001
  11. query_array = []
  12. last_pos = [-1]*1000001
  13. prev_last_pos = [-1]*1000001
  14. bin_tree = [0]*1000001
  15.  
  16. def preprocess(n):
  17. D = {}
  18. counter = 0
  19. for i in range(n):
  20. if t[i] in D:
  21. t[i] = D[t[i]]
  22. else:
  23. D[t[i]] = counter
  24. t[i] = counter
  25. counter += 1
  26.  
  27. def update_bin_tree(n, ind, val):
  28.  
  29. while ind <= n:
  30. bin_tree[ind] += val
  31. ind += ind & (-ind)
  32.  
  33. def get_query(ind):
  34. sol = 0
  35.  
  36. while ind > 0:
  37. sol += bin_tree[ind]
  38. ind -= ind & (-ind)
  39.  
  40. return sol
  41.  
  42.  
  43. def compute(n, q):
  44.  
  45. q_count = 0
  46. for i in range(n):
  47.  
  48. #process the array up to index i
  49. if last_pos[t[i]] != -1:
  50. #push a -2 into last_pos
  51. update_bin_tree(n, last_pos[t[i]]+1, -2)
  52.  
  53. #check for prev_last_pos
  54. if prev_last_pos[t[i]] != -1:
  55. #push a 1 into prev_last_pos
  56. update_bin_tree(n, prev_last_pos[t[i]]+1, 1)
  57.  
  58. #update prev_last_pos
  59. prev_last_pos[t[i]] = last_pos[t[i]]
  60.  
  61. #update last_pos
  62. last_pos[t[i]] = i
  63. update_bin_tree(n, i+1, 1)
  64.  
  65. while (q_count < q) and (query_array[q_count][0] == i):
  66.  
  67. query_solutions[query_array[q_count][2]] = get_query(i+1) - get_query(query_array[q_count][1])
  68. q_count += 1
  69.  
  70.  
  71. if __name__ == '__main__':
  72. n = int(input())
  73.  
  74. t = list(map(int, input().rstrip().split()))
  75.  
  76. preprocess(n)
  77. q = int(input())
  78.  
  79. for i in range(q):
  80. l, r = [int(x) - 1 for x in input().split()]
  81. Q = (r, l, i)
  82. query_array.append(Q)
  83.  
  84. query_array.sort()
  85. compute(n, q)
  86.  
  87. for i in range(q):
  88. print(query_solutions[i])
  89. #print(bin_tree)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement