莫队模版
Posted -ackerman
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了莫队模版相关的知识,希望对你有一定的参考价值。
#include <algorithm> #include <string> #include <cstring> #include <vector> #include <map> #include <stack> #include <set> #include <queue> #include <cmath> #include <cstdio> #include <iomanip> #include <ctime> #include <bitset> #include <cmath> #include <sstream> #include <iostream> #include <unordered_map> #define ll long long #define ull unsigned long long #define ls nod<<1 #define rs (nod<<1)+1 #define pii pair<int,int> #define mp make_pair #define pb push_back #define INF 0x3f3f3f3f #define max(a, b) (a>b?a:b) #define min(a, b) (a<b?a:b) const double eps = 1e-8; const int maxn = 1e6 + 10; const ll MOD = 1e9 + 7; const int mlog=20; int sgn(double a) { return a < -eps ? -1 : a < eps ? 0 : 1; } using namespace std; struct Req { int l,r,id; }q[maxn]; int n,m,B,Bnum,ans; int aa[maxn],pos[maxn]; int ANS[maxn],cnt[maxn]; int cmp(Req a, Req b) { return (pos[a.l] ^ pos[b.l]) ? pos[a.l] < pos[b.l] : ((pos[a.l] & 1) ? a.r < b.r : a.r > b.r); } void upd(int id,int f) { cnt[aa[id]] += f; if (f == 1 && cnt[aa[id]] == 1) ++ans; if (f == -1 && cnt[aa[id]] == 0) --ans; } int main() { scanf("%d", &n); B = sqrt(n); Bnum = ceil((double) n / B); for (int i = 1; i <= Bnum; ++i) { for (int j = (i - 1) * B + 1; j <= i * B; ++j) { pos[j] = i; } } for (int i = 1;i <= n;i++) scanf("%d",&aa[i]); scanf("%d",&m); for(int i = 1; i <= m; ++i) { scanf("%d%d",&q[i].l,&q[i].r); q[i].id = i; } sort(q+1,q+1+m,cmp); int l = 1,r = 0; for (int i = 1;i <= m;i++) { while(r<q[i].r) upd(++r, +1); while(r>q[i].r) upd(r--, -1); while(l<q[i].l) upd(l++, -1); while(l>q[i].l) upd(--l, +1); ANS[q[i].id] = ans; } for (int i = 1;i <= m;i++) printf("%d ",ANS[i]); return 0; }
以上是关于莫队模版的主要内容,如果未能解决你的问题,请参考以下文章