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
题意就是查询区间不同元素的个数,有两种解法。
解法1:离线+树状数组,先把询问离线,并且按照右端点排序,然后从小区间开始,然后树状数组的含义就是指以当前r为结尾的前缀区间的元素种类数,简单点说,就是我当前扫到l , r区间,把l - r区间还没在树状数组上更新的值,更新一遍,在之前已经存在了的值先删掉再更新一遍,确保我确定的元素都是往r靠的,这样才能保证求取区间正确。举个栗子吧:比如我 1 2 2 1 3,当我r移到3的时候,加入前面的1还没在树状数组里更新过(但其实之前已经有读过1了)那就把之前的1的影响删掉,重新在这个3左边这个下标为4的位置给树状数组 add 1.这样确保之后不管我是查询 4 5 或者 1 5,元素1都只算了一次,但都没遗落(想想如果元素1一直在下标1那里,我查询4 5,就不会有1了)
#include<bits/stdc++.h>
using namespace std;
const int maxn=300010;
const int maxq=1000010;
map<int,int>mp;
struct node
{
int l,r,id;//输入查询的区间
//id记录的是每个查询的次序,目的是在对查询区间排序后,能按原来的查询顺序输出结果
};
node q[maxq];
bool cmp(node a,node b)
{
return a.r<b.r;
}
int c[maxn],n;
int lowbit(int x)
{
return x&(-x);
}
int sum(int x)
//int query(int x)
{
int res=0;
while(x)
{
res+=c[x];
x-=lowbit(x);
}
return res;
}
void add(int x,int val)
{
while(x<=n)
{
c[x]+=val;
x+=lowbit(x);
}
}
int a[maxn],ans[maxq];
int main()
{
int i,j,cur,Q;
while(~scanf("%d",&n))
{
mp.clear();
memset(c,0,sizeof(c));
for(i=1;i<=n;i++)
scanf("%d",&a[i]);
scanf("%d",&Q);
for(i=1;i<=Q;i++)
{
scanf("%d%d",&q[i].l,&q[i].r);
q[i].id=i;
}
sort(q+1,q+1+Q,cmp);//按右端点排序
cur=1;
for(i=1;i<=Q;i++)
{
for(j=cur;j<=q[i].r;j++)
{
if(mp.find(a[j])!=mp.end())//在前面出现过
{
add(mp[a[j]],-1);
}
mp[a[j]]=j;
add(j,1);
}
cur=q[i].r+1;
ans[q[i].id]=sum(q[i].r)-sum(q[i].l-1);
}
//一开始cur=1,是1到q[1].r,先对这个小区间操作,然后cur=q[1].r+1
//是q[1].r到q[2].r,继续下去
for(i=1;i<=Q;i++)
printf("%d\n",ans[i]);
}
}
本文介绍一种使用离线+树状数组的方法解决区间不同元素计数问题。通过将查询离线并按右端点排序,利用树状数组高效地统计区间内不同元素的数量。
1万+

被折叠的 条评论
为什么被折叠?



