标签:需要 input script include 反向 bool scan 位置 sample
对于20%的数据,N ≤ 100,M ≤ 1000;
对于40%的数据,N ≤ 3000,M ≤ 200000;
对于100%的数据,N ≤ 50000,M ≤ 200000。
首先反向求解一个nex数组
nex[i]表示co[i]的下一个与其颜色相同的位置。
首先将每个颜色第一次出现的位置标为1
我们首先输入需要查询的区间,根据l排序。
对于在x[i].l之前的点,我们将他们所对应的nex[i]标为1。
然后对于每一个区间求l,r的区间和即可。
有树状数组或线段树求即可。
时间复杂度nlogn
#include<cstdio> #include<algorithm> using namespace std; const int N=50005; int co[N],n,nex[N],tong[1000005],tr[N]; struct A { int xh,l,r,ans; }x[200005]; void chan(int w,int z) { for(;w<=n;w+=w&-w) tr[w]+=z; } int ask(int w) { int re=0; for(;w;w-=w&-w) re+=tr[w]; return re; } bool cmp(const A &t1,const A &t2) { return t1.l==t2.l?t1.r<t2.r:t1.l<t2.l; } bool comp(const A &t1,const A &t2) { return t1.xh<t2.xh; } int main() { int cos=0,m; scanf("%d",&n); for(int i=1;i<=n;i++) scanf("%d",&co[i]),cos=max(cos,co[i]); for(int i=n;i;i--) nex[i]=tong[co[i]],tong[co[i]]=i; for(int i=0;i<=cos;i++) if(tong[i]) chan(tong[i],1); scanf("%d",&m); for(int i=1;i<=m;i++) scanf("%d%d",&x[i].l,&x[i].r),x[i].xh=i; sort(x+1,x+m+1,cmp); for(int i=1,cs=1;i<=m;i++) { for(;cs<x[i].l;cs++) if(nex[cs]) chan(nex[cs],1); x[i].ans=ask(x[i].r)-ask(x[i].l-1); } sort(x+1,x+m+1,comp); for(int i=1;i<=m;i++) printf("%d\n",x[i].ans); return 0; }
标签:需要 input script include 反向 bool scan 位置 sample
原文地址:http://www.cnblogs.com/bzmd/p/6240530.html