DQUERY - D-query
Given a sequence of n numbers a1, a2, ..., an and a number of d-queries. A d-query is a pair (i, j) (1 ≤ i ≤ j ≤ n). For each d-query (i, j), you have to return the number of distinct elements in the subsequence ai, ai+1, ..., aj.
Input
- Line 1: n (1 ≤ n ≤ 30000).
- Line 2: n numbers a1, a2, ..., an (1 ≤ ai ≤ 106).
- Line 3: q (1 ≤ q ≤ 200000), the number of d-queries.
- In the next q lines, each line contains 2 numbers i, j representing a d-query (1 ≤ i ≤ j ≤ n).
Output
- For each d-query (i, j), print the number of distinct elements in the subsequence ai, ai+1, ..., aj in a single line.
Example
Input 5 1 1 2 1 3 3 1 5 2 4 3 5 Output 3 2 3
#include<cstdio> #include<cstring> #include<algorithm> using namespace std; struct Query { int l,r,id; bool operator < (const Query& rhs)const { return r<rhs.r; } }; const int N=3e4+5; int n,q,sum[N],last[1000005],ans[200005],a[N]; Query Q[200005]; void update(int pos,int ope) { if(ope) for(int i=pos;i<=n;i+=i&(-i)) sum[i]+=1; else for(int i=pos;i<=n;i+=i&(-i)) sum[i]-=1; } int query(int pos) { int res=0; for(int i=pos;i>0;i-=i&(-i)) res+=sum[i]; return res; } int main() { scanf("%d",&n); for(int i=1;i<=n;i++) scanf("%d",&a[i]); scanf("%d",&q); for(int i=0;i<q;i++) scanf("%d%d",&Q[i].l,&Q[i].r),Q[i].id=i; sort(Q,Q+q); for(int i=1,k=0;i<=n;i++) { if(last[a[i]])update(last[a[i]],0); update(i,1); last[a[i]]=i; while(Q[k].r==i)ans[Q[k].id]=query(i)-query(Q[k].l-1),k++; } for(int i=0;i<q;i++)printf("%d ",ans[i]); return 0; }