莫队板子

#include<bits/stdc++.h>
using namespace std;
const int maxn=500004;
inline int read() {
    int x=0,w=1;
    char ch=getchar();
    while (ch<'0'||ch>'9') {
        if(ch=='-') w=-1;
        ch=getchar();
    }
    while (ch>='0'&&ch<='9')
        x=(x<<3)+(x<<1)+ch-'0', ch=getchar();
    return x*w;
}
inline void write(int x) {
    if (x<0) 
        putchar('-'), x=-x;
    if (x>9) 
        write(x/10);
    putchar(x%10+'0');
}
int n,s,cnt=0;
int a[maxn],tot[maxn*10],ans[maxn];
int bl[maxn];
struct node{
    int id,l,r;
}query[maxn];
inline bool operator < (const node &x,const node &y){
    int qx=x.l/s,qy=y.l/s;
    if(qx<qy) return true;
    else if(qx==qy&&x.r<y.r) return true;
    return false;
}
inline void del(int x){
    tot[a[x]]--;
    if(!tot[a[x]]) cnt--;
}
inline void ins(int x){
    tot[a[x]]++;
    if(tot[a[x]]==1) cnt++;
}
int main(){
    scanf("%d",&n);
    s=sqrt(n);
    for(register int i=1;i<=n;i++){
        a[i]=read();
    }int m;
    scanf("%d",&m);
    for(register int i=1;i<=m;i++){
        query[i].l=read(),query[i].r=read();
        query[i].id=i;
    }
    sort(query+1,query+m+1);
    int lasl=0,lasr=0;
    for(register int i=1;i<=m;i++){
        int l=query[i].l,r=query[i].r;
        while(lasl<l) del(lasl++);
        while(lasl>l) ins(--lasl);
        while(lasr<r) ins(++lasr);
        while(lasr>r) del(lasr--);
        ans[query[i].id]=cnt;
    }
    for(register int i=1;i<=m;i++) write(ans[i]),putchar('\n');
}

猜你喜欢

转载自www.cnblogs.com/wifimonster/p/10238320.html