English | Vietnamese |
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
乍一看,这道题和前边的那道计算某个区间内的不同数字的和 的那道题很是相似,但是用的却不一样了,这道题目求解是某个区间内不同数字的个数,用的是主席树,这个东西我不会啊,百度脑部,然后又参考的题解
ac代码:
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
#define maxn 100000
using namespace std;
int n,q;
int cnt=0;
struct node{
int l,r;
int sum;
}p[maxn*40];
int la[maxn*10];
int a[maxn];
int root[maxn];
int build(int l,int r)
{
int nc=++cnt;
p[nc].sum=0;
p[nc].l=p[nc].r=0;
if(l==r)
return nc;
int m=(l+r)>>1;
p[nc].l=build(l,m);
p[nc].r=build(m+1,r);
return nc;
}
int updata(int pos,int c,int v,int l,int r)
{
int nc=++cnt;
p[nc]=p[c];
p[nc].sum+=v;
if(l==r) return nc;
int m=(l+r)>>1;
if(m>=pos)
p[nc].l=updata(pos,p[c].l,v,l,m);
else
p[nc].r=updata(pos,p[c].r,v,m+1,r);
return nc;
}
int query(int pos,int c,int l,int r)
{
if(l==r) return p[c].sum;
int m=(l+r)>>1;
if(m>=pos)
return p[p[c].r].sum+query(pos,p[c].l,l,m);
else
return query(pos,p[c].r,m+1,r);
}
int main()
{
scanf("%d",&n);
memset(la,-1,sizeof(la));
for(int i=1;i<=n;i++)
scanf("%d",&a[i]);
root[0]=build(1,n);
for(int i=1;i<=n;i++)
{
int v=a[i];
if(la[v]==-1)
{
root[i]=updata(i,root[i-1],1,1,n);
}
else
{
int t=updata(la[v],root[i-1],-1,1,n);
root[i]=updata(i,t,1,1,n);
}
la[v]=i;
}
scanf("%d",&q);
while(q--)
{
int x,y;
scanf("%d%d",&x,&y);
printf("%d\n",query(x,root[y],1,n));
}
return 0;
}