Advertisement
ashmelev

Count Different - 4

Oct 16th, 2020
2,424
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.67 KB | None | 0 0
  1. #include <iostream>
  2. #include <cassert>
  3. #include <vector>
  4. #include <map>
  5.  
  6. using namespace std;
  7.  
  8. int n;
  9. int m;
  10.  
  11. const int MAX = 20 * 500000;
  12.  
  13. int pos;
  14. int sum[MAX], le[MAX], ri[MAX];
  15.  
  16. typedef int tree;
  17.  
  18. void init(tree nt, tree t) {
  19.     nt[sum] = t[sum];
  20.     nt[le] = t[le];
  21.     nt[ri] = t[ri];
  22. }
  23.  
  24. void update(tree t) {
  25.     t[sum] = t[le][sum] + t[ri][sum];
  26. }
  27.  
  28. tree add(tree t, int tl, int tr, int p, int d) {
  29.     assert(0 <= tl && tl <= p && p < tr && tr <= n + 1);
  30.     tree nt = pos++;
  31.     init(nt, t);
  32.  
  33.     if (tr - tl == 1) {
  34.         nt[sum] += d;
  35.         return nt;
  36.     }
  37.  
  38.     int tc = (tl + tr) / 2;
  39.     if (p < tc)
  40.         nt[le] = add(t[le], tl, tc, p, d);
  41.     else
  42.         nt[ri] = add(t[ri], tc, tr, p, d);
  43.  
  44.     update(nt);
  45.     return nt;
  46. }
  47.  
  48. int getsum(tree t, int tl, int tr, int l, int r) {
  49.     assert(0 <= tl && tl <= l && l < r && r <= tr && tr <= n + 1);
  50.     if (t == 0)
  51.         return 0;
  52.     if (tl == l && tr == r)
  53.         return t[sum];
  54.     int ans = 0;
  55.     int tc = (tl + tr) / 2;
  56.     if (l < tc)
  57.         ans += getsum(t[le], tl, tc, l, min(r, tc));
  58.     if (r > tc)
  59.         ans += getsum(t[ri], tc, tr, max(l, tc), r);
  60.     return ans;
  61. }
  62.  
  63. int main() {
  64.     ios::sync_with_stdio(false);
  65.     cin.tie(nullptr);
  66.     cout.tie(nullptr);
  67.  
  68.     int q;
  69.     cin >> n >> q;
  70.  
  71.     vector<int> a(n), ne(n);
  72.     for (int i = 0; i < n; i++)
  73.         cin >> a[i];
  74.  
  75.     map<int, int> m;
  76.     for (int i = n - 1; i >= 0; i--) {
  77.         if (m.count(a[i]))
  78.             ne[i] = m[a[i]];
  79.         else
  80.             ne[i] = n;
  81.         m[a[i]] = i;
  82.     }
  83.  
  84.     pos = 1;
  85.     vector<tree> vt(n + 1, 0);
  86.     vt[n] = pos++;
  87.     for (int i = n - 1; i >= 0; i--)
  88.         vt[i] = add(vt[i + 1], 0, n + 1, ne[i], 1);
  89.  
  90.     for (int i = 0; i < q; i++) {
  91.         int l, r;
  92.         cin >> l >> r;
  93.         l--;
  94.         cout << r - l - getsum(vt[l], 0, n + 1, l, r) << ' ';
  95.     }
  96. }
  97.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement