统计[l,r]区间内不同数的个数
链接
#include<bits/stdc++.h>
using namespace std;
const int maxn = 2e6;
int n, q;
int cnt[1000000+10];
int a[maxn];
int pos[300];
int res[211111];
struct node
{
int l, r;
int id;
}Q[211111];
bool cmp(node x, node y)
{
return pos[x.l] == pos[y.l]? x.r < y.r:pos[x.l]< pos[y.l];
}
int L = 1, R = 0, ans = 0;
void del(int x)
{
--cnt[a[x]];//
if(cnt[a[x]]==0)--ans;
}
void add(int x)
{
if(0==cnt[a[x]])++ans;
cnt[a[x]]++;
}
int main()
{
scanf("%d", &n);
int sz = (int)sqrt(n);
for(int i = 1;i <= n;i++)
{
scanf("%d", &a[i]);
pos[i] = (i-1)/sz;
}
scanf("%d", &q);
for(int i = 1;i <= q;i++)
{
scanf("%d %d", &Q[i].l, &Q[i].r);
Q[i].id = i;
}
memset(cnt, 0 ,sizeof(cnt));
sort(Q+1, Q+q+1, cmp);
for(int i = 1;i <= q;i++)
{
while(L < Q[i].l)
{
del(L++);
}
while(L > Q[i].l)
{
add(--L);
}
while(R> Q[i].r)
{
del(R--);
}
while(R <Q[i].r)
{
add(++R);
}
res[Q[i].id] = ans;
}
for(int i = 1;i <= q;i++)//
{
printf("%d\n", res[i]);
}
return 0;
}