BZOJ1878[SDOI2009]HH的项链+莫队算法模板
题意:多次询问,求在一个区间中,有多少种珠子;
思路:莫队算法模板题目;
参考:https://www.cnblogs.com/RabbitHu/p/MoDuiTutorial.html
#include <iostream> #include <cstdio> #include <algorithm> using namespace std; const int Block = 233,maxn = 50005,maxm = 200009; int a[maxn],cnt[1000009],ans[maxm],sum=0; #define bel(x) ((x-1)/Block + 1) struct node{ int id,l,r; }q[maxm]; bool cmp (node a,node b) { if(bel(a.l)==bel(b.l)) return a.r<b.r; return bel(a.l) < bel(b.l); } void del (int x) { cnt[x] --; if(!cnt[x])sum--; } void add (int x) { if(cnt[x]==0)sum++; cnt[x] ++; } int main(){ int n,m; scanf("%d",&n); for(int i=1; i<=n; i++)scanf("%d", &a[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 ql = 1,qr = 0; for(int i=1; i<=m; i++) { while(ql < q[i].l) del(a[ql++]); while(ql > q[i].l) add(a[--ql]); while(qr < q[i].r) add(a[++qr]); while(qr > q[i].r) del(a[qr--]); ans[q[i].id] = sum; } for(int i=1; i<=m; i++) printf("%d\n", ans[i]); return 0; }
skr