题目链接
DQUERY - D-query
English | Vietnamese |
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,然后是n个数,再给出m,m个询问,对于每个询问l,r,输出区间[l,r]里面不同的值有多少个。
题解:
可以用一个map离散化,倒着对序列进行操作,对于每个i建树时,如果a[i]出现过,则在map[a[i]]处减去1,然后询问时直接对根为root[l]的树进行询问就可以了。
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<vector>
#include<queue>
#include<stack>
#include<map>
using namespace std;
#define rep(i,a,n) for (int i=a;i<n;i++)
#define per(i,a,n) for (int i=n-1;i>=a;i--)
#define pb push_back
#define fi first
#define se second
typedef vector<int> VI;
typedef long long ll;
typedef pair<int,int> PII;
const int inf=0x3fffffff;
const ll mod=1000000007;
const int maxn=30000+100;
int n,m,cnt,a[maxn],root[maxn];
struct node{int l,r,sum;}T[maxn*40];
map<int,int> mp;
void update(int l,int r,int& x,int y,int pos,int val)
{
T[++cnt]=T[y],T[cnt].sum+=val;
x=cnt;
if(l==r) return;
int mid=(l+r)/2;
if(pos<=mid) update(l,mid,T[x].l,T[y].l,pos,val);
else update(mid+1,r,T[x].r,T[y].r,pos,val);
}
int query(int l,int r,int root,int k)
{
int ans=0;
if(l==r) return T[root].sum;
int mid=(l+r)/2;
if(mid<k) return T[T[root].l].sum+query(mid+1,r,T[root].r,k);
else return query(l,mid,T[root].l,k);
}
int main()
{
scanf("%d",&n);
rep(i,1,n+1) scanf("%d",&a[i]);
mp.clear();
per(i,1,n+1)
{
if(mp.find(a[i])==mp.end())
{
update(1,n,root[i],root[i+1],i,1);
}
else
{
update(1,n,root[i],root[i+1],mp[a[i]],-1);
update(1,n,root[i],root[i],i,1);
}
mp[a[i]]=i;
}
scanf("%d",&m);
while(m--)
{
int x,y;
scanf("%d%d",&x,&y);
printf("%d\n",query(1,n,root[x],y));
}
return 0;
}