HH的项链 树状数组动态维护前缀


#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
const int N=2000000+9;
int C[N],flower[N],pre[N],head[N];
int A[N],l[N],r[N],ans[N];
int cmp(int i,int j){
	return r[i]<r[j];
}
int lowbit(int t){
	return t&(-t);
}
void update(int t,int delta){
	while(t<N)
		C[t]+=delta,t+=lowbit(t);
}
int query(int t){
	int tmp=0;
	while(t>0)
		tmp+=C[t],t-=lowbit(t);
	return tmp;
}
int main()
{
	//freopen("in.txt","r",stdin);
	int n,c,m;
	scanf("%d%d%d",&n,&c,&m);
	for(int i=1;i<=n;++i)scanf("%d",&flower[i]);
	for(int i=1;i<=m;++i)scanf("%d%d",&l[i],&r[i]),A[i]=i;
	sort(A+1,A+1+m,cmp);
    int cur=1;
    for(int i=1;i<=n;++i)
    {
    	int ty=flower[i];
    	if(head[ty]==0)head[ty]=i;
    	else
    	{
    		pre[i]=head[ty],head[ty]=i;
    		update(pre[i],1);
    		if(pre[pre[i]])update(pre[pre[i]],-1);
    	}
    	while(r[A[cur]]==i)
    	{
    		ans[A[cur]]=query(r[A[cur]])-query(l[A[cur]]-1);
    		++cur;
    	}
    }
    for(int i=1;i<=m;++i)printf("%d\n",ans[i]);
    return 0;
}
posted @ 2018-08-23 20:00  EM-LGH  阅读(192)  评论(0编辑  收藏  举报