DescriptionHH has a chain of beautiful shells. HH believes that the different shells will bring good luck, so every time after the walk, he will take out ashells, thinking about what they mean. HH keeps collecting new shells, so his necklace is getting longer. One day, he suddenly made aquestion: How many different shells are involved in a certain piece of shell? The question is difficult to answer ... Because the necklace is too long. So, he onlyto help the wise you, to solve the problem. InputFirst 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. n≤50000,m≤200000. Output
M 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————————————————————————————————This problem we maintain the pre[i of each point]
That is, for each position I, preprocessing out pre[i] means I left to i the nearest J makes A[i]==a[j]
Then we enumerate the right endpoint and maintain the answer to each left endpoint to be spicy.
That is, when you sweep to a point I, s[pre[i]]--s[i]++ maintain the differential of the tree array.
Because you're going to have this point right now, so the position of the same color in the previous interval has no effect on the current and the subsequent bands.
#include <cstdio>#include<cstring>#include<algorithm>#include<vector>Const intm=1e5+7;intRead () {intans=0, f=1, c=GetChar (); while(c<'0'|| C>'9'){if(c=='-') f=-1; C=GetChar ();} while(c>='0'&&c<='9') {ans=ans*Ten+ (C-'0'); C=GetChar ();} returnans*F;}intn,m,k;intans[5*m],last[ the*m],pre[ the*M],s[m];structpos{intX,id;}; Std::vector<pos>Q[m];intL,r;#defineLowbit (x) x&-xvoidInsintXintV) { while(x<=n) s[x]+=v,x+=lowbit (x);}intQueryintx) { intsum=0; while(x) sum+=s[x],x-=lowbit (x); returnsum;}intMain () {n=read (); for(intI=1; i<=n;i++) {k=read (); if(Last[k]) pre[i]=Last[k]; LAST[K]=i; } m=read (); for(intI=1; i<=m;i++) L=read (), R=read (), Q[r].push_back ((POS) {L1, i}); for(intI=1; i<=n;i++){ if(Pre[i]) ins (pre[i],-1); Ins (i,1); intMx=q[i].size (), now=query (i); for(intj=0; j<mx;j++){ intx=q[i][j].x; Ans[q[i][j].id]=now-query (x); } } for(intI=1; i<=m;i++) printf ("%d\n", Ans[i]); return 0;}
View Code
Bzoj 1878: [Sdoi2009]hh Necklace--Tree array + differential