DESCRIPTIONHH has a chain of beautiful shells. HH believes that different shells will bring good luck, so after each walk, he will take out a shell and think about what they mean. HH keeps collecting new shells, so his necklace is getting longer. One day, he suddenly raised a question: how many different shells are included in a certain piece of shell? The question is difficult to answer ... Because the necklace is too long. So he had to ask the wise you to solve the problem. Input first line: An integer n that represents the length of the necklace. Second line: n integers representing the number of shells in the necklace (integers numbered 0 to 1000000, in turn). Line three: An integer m that indicates the number of HH queries. Next m line: two integers per line, L and R (1≤l≤r≤n), indicating the interval of the inquiry. OUTPUTM lines, one integer per line, in turn, to ask the corresponding answer. Sample Input6
1 2 3 4 3 5
3
1 2
3 5
2 6
Sample Output2
2
4
HINT
For 20% of data, n≤100,m≤1000;
For 40% of data, n≤3000,m≤200000;
For 100% of data, n≤50000,m≤200000.
Ideas
Offline processing +bit
String the same color nodes into a chain. Offline processing of all inquiries, for n locations to build a bit, for more than one color, we have this color in the left end of the interval to the right of the first occurrence of the position is set to 1, when the color moved out of the interval to the left end of the line when we set the next occurrence of the color to 1, so you can use the bit to
Code
1#include <cstdio>2#include <cstring>3#include <algorithm>4 using namespacestd;5 6 Const intN = 1e6+5;7 structNode {8 intL,r,id;9 BOOL operator< (Constnode& RHS)Const {Ten returnl<rhs.l| | (l==rhs.l&&r<RHS.R); One } A }que[n]; - - intN,m,c[n],mx,a[n],ans[n]; the intFront[n],next[n]; - - voidAddintXintv) { - for(; x<=n;x+=x&-x) c[x]+=v; + } - intSumintx) { + intres=0; A for(;x>0; x-=x&-x) res+=C[x]; at returnRes; - } - - intMain () { -scanf"%d",&n); - for(intI=1; i<=n;i++) { inscanf"%d",&a[i]); -mx=Max (mx,a[i]); to } + for(intI=n;i>0; i--)//add positive sequence into chain in reverse order -next[i]=front[a[i]],front[a[i]]=i; the for(intI=1; i<=mx;i++) * if(Front[i]) Add (Front[i],1); $scanf"%d",&m);Panax Notoginseng for(intI=1; i<=m;i++) { -scanf"%d%d",&que[i].l,&QUE[I].R); theQue[i].id=i; + } ASort (que+1, que+m+1); the intL=1; + for(intI=1; i<=m;i++) { - while(l<QUE[I].L) { $ if(Next[l]) Add (Next[l],1); $l++; - } -Ans[que[i].id]=sum (QUE[I].R)-sum (que[i].l-1); the } - for(intI=1; i<=m;i++)Wuyiprintf"%d\n", Ans[i]); the return 0; -}
Bzoj 1878 [Sdoi2009]hh's Necklace (offline processing +bit)