BZOJ1878[SDOI2009]HH's necklace + Mo team algorithm template

The meaning of the question: ask many times, how many kinds of beads are there in an interval;

Ideas: Mo team algorithm template topic;

Reference : 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;
}

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324819167&siteId=291194637