Advertisement
DiegoDF1445

CSES - Distinct Values Queries

May 8th, 2020
1,580
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.97 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2.  
  3. using namespace std;
  4.  
  5. void upd(int i, int n, int v, vector<int>& cnt){
  6.     i++;
  7.     while(i <= n) cnt[i] += v, i += (i&-i);
  8. }
  9.  
  10. int rtv(int i, vector<int>& cnt){
  11.     i++;
  12.     int s = 0;
  13.     while(i) s += cnt[i], i -= (i&-i);
  14.     return s;
  15. }
  16.  
  17. int main(){
  18.     cin.tie(0);
  19.     ios::sync_with_stdio(0);
  20.     int n, q, c = 0, a, b, l = 0;
  21.     cin >> n >> q;
  22.     vector<int> x(n), cnt(n+1), p(n, -1), ans(q);
  23.     map<int, int> m;
  24.     for(int &z : x){
  25.         cin >> z;
  26.         if(m.find(z) != m.end()) z = m[z];
  27.         else z = m[z] = c++;
  28.     }
  29.     vector< tuple<int, int, int> > qry(q);
  30.     for(int i = 0; i < q; i++){
  31.         cin >> a >> b;
  32.         qry[i] = {--b, --a, i};
  33.     }
  34.     sort(qry.begin(), qry.end());
  35.     upd(0, n, 1, cnt), p[0] = 0;
  36.     for(auto &t : qry){
  37.         tie(b, a, c) = t;
  38.         while(l < b){
  39.             l++;
  40.             if(p[x[l]] != -1) upd(p[x[l]], n, -1, cnt);
  41.             upd(l, n, 1, cnt), p[x[l]] = l;
  42.         }
  43.         ans[c] = rtv(b, cnt);
  44.         if(a) ans[c] -= rtv(a-1, cnt);
  45.         l = b;
  46.     }
  47.     for(int &z : ans) cout << z << "\n";
  48. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement