题意:
求区间不同数的个数。
思路:
离线处理(莫队/分块)
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef pair<LL,LL>PII;
const int N=2e5+10;
int n,q;
int a[N];
int tim[N];
struct asd{
int Left,Right;
int id;
int res;
}e[N];
int pos[N];
bool cmp(asd x,asd y){
if(pos[x.Left]==pos[y.Left]) return x.Right<y.Right;
return x.Left<y.Left;
}
void solve(){
int ans = 0;
memset(tim,0,sizeof(tim));
for(int i=0, L=1,R=0;i < q;i++){
while(R < e[i].Right){
R++;
if(!tim[a[R]]) ans++;
tim[a[R]]++;
}
while(R > e[i].Right){
if(tim[a[R]] == 1) ans--;
tim[a[R]]--;
R--;
}
while(L > e[i].Left){
L--;
if(!tim[a[L]]) ans++;
tim[a[L]]++;
}
while(L < e[i].Left){
if(tim[a[L]] == 1) ans--;
tim[a[L]]--;
L++;
}
e[e[i].id].res = ans;
}
}
vector<int>xs;
int main(){
scanf("%d",&n);
int block=(int)sqrt(n);
for(int i=1;i<=n;i++)
{
scanf("%d",&a[i]);
xs.push_back(a[i]);
pos[i]=(i-1)/block+1;
}
sort(xs.begin(),xs.end());
for(int i=1;i<=n;i++)
a[i] = lower_bound(xs.begin(),xs.end(),a[i]) - xs.begin() + 1;
scanf("%d",&q);
for(int i=0;i<q;i++){
scanf("%d%d",&e[i].Left,&e[i].Right);
e[i].id = i;
}
sort(e,e+q,cmp);
solve();
for(int i=0;i<q;i++)
printf("%d\n",e[i].res);
return 0;
}