Different Integers

题意:有Q个区间,问每个区间[L,R]有多少个不同的数字

思路:BIT

#include<bits/stdc++.h>
#define PI acos(-1.0)
#define pb push_back
#define F first
#define S second
using namespace std;
typedef long long ll;
const int N=3e5+5;
const int MOD=1e9+7;
int a[N],tree[N];
template <class T>
bool sf(T &ret){ //Faster Input
    char c; int sgn; T bit=0.1;
    if(c=getchar(),c==EOF) return 0;
    while(c!='-'&&c!='.'&&(c<'0'||c>'9')) c=getchar();
    sgn=(c=='-')?-1:1;
    ret=(c=='-')?0:(c-'0');
    while(c=getchar(),c>='0'&&c<='9') ret=ret*10+(c-'0');
    if(c==' '||c=='\n'){ ret*=sgn; return 1; }
    while(c=getchar(),c>='0'&&c<='9') ret+=(c-'0')*bit,bit/=10;
    ret*=sgn;
    return 1;
}
int ans[N],pre[N],n,q;
struct node{
    int l,r,id;
    bool operator < (const node& obj)const{
        return r<obj.r;
    }
}query[N];
 
void add(int x,int v){
    for(int i=x;i<=200000;i+=(i&(-i))) tree[i]+=v;
}
 
int sum(int pos){
    int res=0;
    for(int i=pos;i;i-=(i&(-i)))  res+=tree[i];
    return res;
}
 
int main(void){
//    ios::sync_with_stdio(false);
//    cin.tie(0);cout.tie(0);
    while( (scanf("%d%d",&n,&q))==2){
        memset(tree,0ll,sizeof tree);
        memset(pre,0,sizeof pre);
        memset(ans,0,sizeof ans);
        for(int i=1;i<=n;i++)   sf(a[i]),a[i+n]=a[i];
        for(int i=1;i<=q;i++){
            int l,r;
            sf(l);sf(r);
//            if(l==r)    query[i].r--;
            query[i].l=r,query[i].r=n+l;
            query[i].id=i;
        }
        sort(query+1,query+1+q);
        int now=1;
        for(int i=1;i<=q;i++){
            for(;now<=query[i].r;now++){
                if(pre[a[now]]!=0){
                    add(pre[a[now]],-1);
                }
                add(now,1);
                pre[a[now]]=now;
            }
            ans[query[i].id]=sum(query[i].r)-sum(query[i].l-1);
        }
        for(int i=1;i<=q;i++)   printf("%d\n",ans[i]);
    }
    return 0;
}