Description
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
题目大意
在一个长度为n的数组中给定m次查询,每一次查询输入l和r,表示数组区间【l,r】。要求输出每一次查询时在要求的区间里不同数的种类。
代码
#include<iostream>
#include<algorithm>
#include<memory.h>
#include<cmath>
#include<cstdio>
typedef long long ll;
using namespace std;
int n,m;
struct node
{
int l,r,id;
};
node a[200005];
int sz,sum[30005],ans,Ans[200005],num[1000005];
bool cmp(node a,node b)
{
if(a.l/sz==b.l/sz)
return a.r<b.r;
return a.l<b.l;
}
int main()
{
int i,j;
while(cin>>n)
{
memset(num,0,sizeof(num));
sz=sqrt(n*1.0);
for(i=1;i<=n;i++)
scanf("%d",&sum[i]);
cin>>m;
for(i=1;i<=m;i++)
{
cin>>a[i].l>>a[i].r;
a[i].id=i;
}
sort(a+1,a+1+m,cmp);
int l=1,r=0;
ans=0;
for(i=1;i<=m;i++)
{
int id=a[i].id;
if(a[i].l==a[i].r)
{
Ans[id]=1;
continue;
}
if(r<a[i].r)
{
for(j=r+1;j<=a[i].r;j++)
{
if(num[sum[j]]==0)
{
ans++;
}
num[sum[j]]++;
}
}
else
{
for(j=r;j>a[i].r;j--)
{
num[sum[j]]--;
if(num[sum[j]]==0)
ans--;
}
}
r=a[i].r;
if(l<a[i].l)
{
for(j=l;j<a[i].l;j++)
{
num[sum[j]]--;
if(num[sum[j]]==0)
ans--;
}
}
else
{
for(j=l-1;j>=a[i].l;j--)
{
if(num[sum[j]]==0)
ans++;
num[sum[j]]++;
}
}
l=a[i].l;
Ans[id]=ans;
}
for(i=1;i<=m;i++)
printf("%d\n",Ans[i]);
}
return 0;
}