首先,题意依旧不用说了;这道题要我们求的是区间有多少个不同的数字。我们发现,假设数组pos[i]表示的是:这个位置是不是数字i所出现的最后一个位置(目前),说以我们只需将输入的询问的数组按照右端点从小到大排序,每当我们遇到一个点时,我们只需将他的pos更新为last即可。这样我们只需用线段树维护pos数组即可。
Talk is cheap,show you the code
#include <bits/stdc++.h>
#define ll long long
using namespace std;
const int N=2e5+5;
const int M=1e6+5;
int letter[N];//读入数组
int L[N],R[N];//线段树的左右端点
int ans[N];//保存答案
int sum[N];//线段树
int pos[M];//记录数上一次出现的位置
int n,m;
struct node
{
int x,y;//左右端点
int cnt;//读入的顺序
bool operator < (const node &b)const
{
return y<b.y;
}
} a[N];
//线段树高清无码模板
void build(const int &l,const int &r,const int &now)
{
L[now]=l;
R[now]=r;
sum[now]=0;
if (l==r)
{
return;
}
int mid=(l+r)>>1;
build(l,mid,now<<1);
build(mid+1,r,now<<1|1);
}
void update(const int &x,const int &now,const int &d)
{
if (L[now]==R[now])
{
sum[now]+=d;
return;
}
int mid=(L[now]+R[now])>>1;
if (x<=mid)update(x,now<<1,d);
else update(x,now<<1|1,d);
sum[now]=sum[now<<1]+sum[now<<1|1];
}
int query(const int &l,const int &r,const int &now)
{
if (L[now]==l&&R[now]==r)return sum[now];
int mid=(L[now]+R[now])>>1;
if (r<=mid)return query(l,r,now<<1);
else if (l>mid)return query(l,r,now<<1|1);
else return query(l,mid,now<<1)+query(mid+1,r,now<<1|1);
sum[now]=sum[now<<1]+sum[now<<1|1];
}
int main()
{
scanf("%d",&n);
build(1,n,1);
for (int i=1; i<=n; i++)
scanf("%d",&letter[i]);
scanf("%d",&m);
for (int i=1; i<=m; i++)
{
scanf("%d%d",&a[i].x,&a[i].y);
a[i].cnt=i;//小trick
}
sort(a+1,a+1+m);
int last=0;
for (int i=1; i<=m; i++)
{
while (last<a[i].y)
{
last++;
update(last,1,1);
if (pos[letter[last]])
update(pos[letter[last]],1,-1);
pos[letter[last]]=last;
}
ans[a[i].cnt]=query(a[i].x,a[i].y,1);
}
for (int i=1; i<=m; i++)
printf("%d\n",ans[i]);
return 0;
}