Advertisement
milon34

range unique value find with offline query

Feb 19th, 2023
51
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.02 KB | None | 0 0
  1. intput:
  2. 4
  3. 1 2 3 3
  4. 2
  5. 1 3
  6. 3 4
  7. output:3 1
  8.  
  9.  
  10. #include <bits/stdc++.h>
  11. using namespace std;
  12. #define ll long long int
  13. const ll mx = 2e5 + 100;
  14. ll tree[mx * 3];
  15. int arr[mx * 3];
  16.  
  17. void build(ll id, ll b, ll e) {
  18.     if (b == e) {
  19.         tree[id] = arr[b];
  20.         return;
  21.     }
  22.     int mid = (b + e) >> 1;
  23.     build(2 * id, b, mid);
  24.     build(2 * id + 1, mid + 1, e);
  25.     tree[id] = tree[id * 2] + tree[id * 2 + 1];
  26. }
  27.  
  28. void update(ll id, ll b, ll e, ll i, ll val) {
  29.     if (e < i || b > i) {
  30.         return;
  31.     }
  32.     if (e == i && b == i) {
  33.         tree[id] = val;
  34.         return;
  35.     }
  36.     ll mid = (b + e) >> 1;
  37.     update(2 * id, b, mid, i, val);
  38.     update(2 * id + 1, mid + 1, e, i, val);
  39.     tree[id] = tree[id * 2] + tree[id * 2 + 1];
  40. }
  41.  
  42. ll query(ll id, ll b, ll e, ll i, ll j) {
  43.     if (b > j || e < i) {
  44.         return 0;
  45.     }
  46.     if (i <= b && j >= e) {
  47.         return tree[id];
  48.     }
  49.     ll mid = (b + e) >> 1;
  50.     ll left = query(id * 2, b, mid, i, j);
  51.     ll right = query(id * 2 + 1, mid + 1, e, i, j);
  52.     return left + right;
  53. }
  54.  
  55.  
  56. int main() {
  57.     ios_base::sync_with_stdio(false);
  58.     cin.tie(0);
  59.     int n;
  60.     cin >> n;
  61.     int a[n + 1];
  62.     for (int i = 1; i <= n; i++) {
  63.         cin >> a[i];
  64.     }
  65.     int q;
  66.     cin >> q;
  67.     vector<pair<int, int>> vec[n + 1];
  68.     for (int i = 1; i <= q; i++) {
  69.         int l, r;
  70.         cin >> l >> r;
  71.         vec[r].push_back({l, i});
  72.     }
  73.     memset(arr, 0, sizeof(arr));
  74.     build(1, 1, n);
  75.     map<int, int> mp;
  76.     ll ans[n + 1] = {0};
  77.     for (int i = 1; i <= n; i++) {
  78.         if (mp.find(a[i]) == mp.end()) {
  79.             update(1, 1, n, i, 1);
  80.         } else {
  81.             update(1, 1, n, mp[a[i]], 0);
  82.             update(1, 1, n, i, 1);
  83.         }
  84.         mp[a[i]] = i;
  85.         for (auto x:vec[i]) {
  86.             int l = x.first;
  87.             int id = x.second;
  88.             ans[id] = query(1, 1, n, l, i);
  89.         }
  90.     }
  91.     for (int i = 1; i <= q; i++) {
  92.         cout << ans[i] << " ";
  93.     }
  94.  
  95.  
  96.     return 0;
  97. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement