Advertisement
hkshakib

Untitled

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