Advertisement
newb_ie

MO's Algorithm (Distinct Elements in a Range)

May 23rd, 2021
269
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.52 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. const int maxN = 1e6 + 100;
  5. const int block = 560;
  6. pair<pair<int,int>,int> query[maxN]; // l,r,and query index;
  7. int input[maxN],res[maxN],freq[maxN];
  8.  
  9. int ans = 0;
  10.  
  11. void add (int pos) {
  12.     ++freq[input[pos]];
  13.     if (freq[input[pos]] == 1) ++ans;
  14. }
  15.  
  16. void remove (int pos) {
  17.     --freq[input[pos]];
  18.     if (freq[input[pos]] == 0) --ans;
  19. }
  20.  
  21. int main () {
  22.      ios::sync_with_stdio(false);
  23.      cin.tie(nullptr);
  24.      cout.tie(nullptr);
  25.      int T = 1;
  26.      //~ cin >> T;
  27.      for (int test_case = 1; test_case <= T; ++test_case) {
  28.          int n,q;
  29.          cin >> n;
  30.          for (int i = 0; i < n; ++i) cin >> input[i];
  31.          cin >> q;
  32.          for (int i = 0; i < q; ++i) {
  33.              cin >> query[i].first.first >> query[i].first.second;
  34.              query[i].second = i;
  35.              --query[i].first.first,--query[i].first.second;
  36.          }
  37.          sort (query,query + q,[&](pair<pair<int,int>,int> a,pair<pair<int,int>,int> b) {
  38.              if (a.first.first / block != b.first.first / block) {
  39.                  return a.first.first / block < b.first.first / block;
  40.              }
  41.              return a.first.second < b.first.second;
  42.          });
  43.          int l = 0,r = -1;
  44.          for (int i = 0; i < q; ++i) {
  45.              while (l > query[i].first.first) --l,add(l);
  46.              while (r < query[i].first.second) ++r,add(r);
  47.              while (l < query[i].first.first) remove(l),++l;
  48.              while (r > query[i].first.second) remove(r),--r;
  49.              res[query[i].second] = ans;
  50.          }
  51.          for (int i = 0; i < q; ++i) cout << res[i] << '\n';
  52.      }
  53.      //~ cerr << "Time elapsed :" << clock() * 1000.0 / CLOCKS_PER_SEC << " ms" << '\n';
  54. }
  55.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement