bzoj2743 采花 树状数组

       令pre[i]表示在i之前和i同色的与i最近的点,则答案相当于统计有多少点,满足pre[]在(l,r)区间中,而pre[pre[]]不再(l,r)中。离线树状数组即可。

AC代码如下:

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#define N 1000005
using namespace std;

int n,cnt,m,pt,tot,c[N],fst[N],pnt[N],id[N],nxt[N],ans[N],pre[N],last[N];
int read(){
	int x=0; char ch=getchar();
	while (ch<'0' || ch>'9') ch=getchar();
	while (ch>='0' && ch<='9'){ x=x*10+ch-'0'; ch=getchar(); }
	return x;
}
void add(int x,int y,int z){
	pnt[++tot]=y; id[tot]=z; nxt[tot]=fst[x]; fst[x]=tot;
}
void ins(int x,int t){
	for (; x<=n; x+=x&-x) c[x]+=t;
}
int getsum(int x){
	int t=0; for (; x; x-=x&-x) t+=c[x]; return t;
}
int main(){
	n=read(); cnt=read(); m=read(); int i,x,y;
	for (i=1; i<=n; i++){
		x=read(); pre[i]=last[x]; last[x]=i;
	}
	for (i=1; i<=m; i++){
		x=read(); y=read(); add(y,x,i);
	}
	for (y=1; y<=n; y++){
		if (pre[y]){ pt++; ins(pre[y],1); }
		if (pre[pre[y]]){ pt--; ins(pre[pre[y]],-1); }
		for (i=fst[y]; i; i=nxt[i]){
			x=pnt[i];
			ans[id[i]]=pt-getsum(x-1);
		}
	}
	for (i=1; i<=m; i++) printf("%d\n",ans[i]);
	return 0;
}


by lych

2016.4.2

你可能感兴趣的:(树状数组)