hkshakib

Untitled

Mar 19th, 2020
162
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.73 KB | None | 0 0
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3. const int maxn = 1e5+10;
  4. int arr[maxn], ans[maxn], cnt[maxn], n, q, block_size;
  5. struct Query
  6. {
  7. int index, L, R;
  8. bool operator<(const Query& other)
  9. {
  10. return L/block_size < other.L/block_size ||
  11. (L/block_size == other.L/block_size && R<other.R);
  12. }
  13.  
  14. } query[maxn];
  15.  
  16. int distinct_elements;
  17.  
  18. void add(int idx)
  19. {
  20. cnt[arr[idx]]++;
  21. if(cnt[arr[idx]]==1)
  22. distinct_elements++;
  23. }
  24. void del(int idx)
  25. {
  26. cnt[arr[idx]]--;
  27. if(cnt[arr[idx]]==0)
  28. distinct_elements--;
  29. }
  30. int main()
  31. {
  32. //freopen("t.txt","w",stdout);
  33. int t,cas=1;
  34. scanf("%d",&t);
  35. while(t--)
  36. {
  37. memset(ans,0,sizeof(ans));
  38. scanf("%d %d",&n,&q);
  39. for(int i=0; i<n; i++)
  40. {
  41. scanf("%d", &arr[i]);
  42. }
  43. block_size = sqrt(n);
  44. for(int i=0; i<q; i++)
  45. {
  46. scanf("%d %d",&query[i].L,&query[i].R);
  47. --query[i].L;
  48. --query[i].R;
  49. query[i].index=i;
  50. }
  51. sort(query, query+q);
  52. int curL = 0, curR =-1;
  53. distinct_elements = 0;
  54. for(int i=0; i<q; i++)
  55. {
  56. int query_index = query[i].index;
  57. int l = query[i].L;
  58. int r = query[i].R;
  59.  
  60. while(curL<l)
  61. del(curL++);
  62. while(curL>l)
  63. add(--curL);
  64. while(curR<r)
  65. add(++curR);
  66. while(curR>r)
  67. del(curR--);
  68. ans[query_index] = distinct_elements;
  69. }
  70. printf("Case %d:\n",cas++);
  71. for(int i=0; i<q; i++)
  72. {
  73. printf("%d\n", ans[i]);
  74. }
  75. }
  76. }
Advertisement
Add Comment
Please, Sign In to add comment