D − q u e r y D-query D−query
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
给出一个序列,每次询问区间[l , r]有多少个不同的数。
一开始自然想到权值线段树+离散化,但是貌似行不通,然后就去学习了一下,发现都是用普通的线段树的,嗯…
还是序列的每个位置都开一棵线段树,根节点只存0或1,0表示没有,1表示存在,如果开到序列的某个位置的时候这个元素已经出现过了的话,就把这个元素往后移,它原来出现的位置-1,当前位置+1,也就是每棵线段树只存所有元素最后出现的位置。
这样每次查询区间[l , r]的时候只要找第r棵线段树中>l的节点存的元素个数就行了。
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int maxn = 3e5+7;
const int maxv = 1e6+7;
int n,m,seq[maxn],root[maxn],vis[maxv];
struct haha_Tree{
struct Node{
int l,r,sum;
}node[maxn<<7];
int cnt;
haha_Tree(){cnt = 0;}
void build(int l,int r,int &now){
node[now=++cnt].sum = 0;
if(l+1==r) return;
int mid = (l+r)>>1;
build(l,mid,node[now].l);
build(mid,r,node[now].r);
}
void update(int l,int r,int &now,int pre,int pos,int val){
node[now=++cnt] = node[pre];
node[now].sum+=val;
if(l+1==r) return;
int mid = (l+r)>>1;
if(pos<mid) update(l,mid,node[now].l,node[pre].l,pos,val);
else update(mid,r,node[now].r,node[pre].r,pos,val);
}
int query(int l,int r,int rt,int pos){
if(l>=pos) return node[rt].sum;
if(pos>=r) return 0;
int mid = (l+r)>>1;
return query(l,mid,node[rt].l,pos)+query(mid,r,node[rt].r,pos);
}
}Seg_Tree;
int main(){
scanf("%d",&n);
for(int i=1;i<=n;i++) scanf("%d",&seq[i]);
Seg_Tree.build(1,n+1,root[0]);
for(int i=1;i<=n;i++){
if(!vis[seq[i]]) Seg_Tree.update(1,n+1,root[i],root[i-1],i,1);
else{
Seg_Tree.update(1,n+1,root[i],root[i-1],vis[seq[i]],-1);
Seg_Tree.update(1,n+1,root[i],root[i],i,1);
}
vis[seq[i]] = i;
}
scanf("%d",&m);
for(int i=1;i<=m;i++){
int l,r;
scanf("%d %d",&l,&r);
printf("%d\n",Seg_Tree.query(1,n+1,root[r],l));
}
return 0;
}