Abrar_Al_Samit

Mo's Algorithm

Jul 15th, 2021
161
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.54 KB | None | 0 0
  1. const int block_size = 800;
  2.  
  3.  
  4. // 0 based indexing
  5. class MosAlgorithm {
  6. public:
  7.     struct Query {
  8.         int l, r, index;
  9.         bool operator< (Query o) const {
  10.             return make_pair(make_pair(l/block_size, r), index) < make_pair(make_pair(o.l/block_size, o.r), o.index);
  11.         };
  12.     };
  13.     int N, M; // N -> Query count, M -> Max element
  14.     vector<Query>queries;
  15.     vector<int>range, A;
  16.     MosAlgorithm(vector<pair<int,int>>&_queries) {
  17.         N = _queries.size();
  18.         for(int i=0; i<N; ++i) {
  19.             Query q = {_queries[i].first, _queries[i].second, i};
  20.             queries.push_back(q);
  21.         }
  22.         sort(queries.begin(), queries.end());
  23.     }
  24.     void Hash(vector<int>a) {
  25.         map<int,int>H;
  26.         A = a;
  27.         for(int i=0; i<A.size(); ++i) H[A[i]] = 0;
  28.         int cur = 0;
  29.         for(auto &it : H) it.second = cur++;
  30.         for(int i=0; i<A.size(); ++i) A[i] = H[A[i]];
  31.         M = cur;
  32.         range.resize(M+1, 0);
  33.     }
  34.     vector<int>process() {
  35.         int L = 0, R = -1, cur = 0;
  36.         vector<int>ret(N);
  37.         for(Query q : queries) {
  38.             while(L > q.l) {
  39.                 if(++range[A[--L]]==1) ++cur;
  40.             }
  41.             while(R < q.r) {
  42.                 if(++range[A[++R]]==1) ++cur;
  43.             }
  44.             while(L < q.l) {
  45.                 if(--range[A[L++]]==0) --cur;
  46.             }
  47.             while(R > q.r) {
  48.                 if(--range[A[R--]]==0) --cur;
  49.             }
  50.             ret[q.index] = cur;
  51.         }
  52.         return ret;
  53.     }
  54. };
Advertisement
Add Comment
Please, Sign In to add comment