DQUERY - 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
思路:假如右区间 R 固定,我们可以记录每一个数最后出现的位置的下标,对应位置的 val 为1
例:对序列 1 1 2 1 3 我们查询 [l , 5],得到的就是 0 0 1 1 1,然后利用前缀和就可以查询了。
那么对于右区间 R 不固定的情况,我们就可以根据右区间的不同来维护。如果不使用主席树,就得对右区间先排序,然后利用线段树。
否则就只能用主席树,记录所有历史信息。 主席树每一次更新都判断是否之前存在,若存在,则 先消去原位置,再更新新位置, 不存在就直接更新。
主席树:
#include<bits/stdc++.h>
#define debug(x) cout << "[" << #x <<": " << (x) <<"]"<< endl
#define pii pair<int,int>
#define clr(a,b) memset((a),b,sizeof(a))
#define rep(i,a,b) for(int i = a;i < b;i ++)
#define pb push_back
#define MP make_pair
#define LL long long
#define ull unsigned LL
#define ls i << 1
#define rs i << 1 + 1
#define INT(t) int t; scanf("%d",&t)
using namespace std;
const int maxn = 3e4 + 10;
const int M = maxn * 40;
int pos[M];
int tot = 0,T[maxn];
int C[M],lson[M],rson[M];
int n;
int build(int l,int r){
int rt = tot ++;
if(l != r){
int mid = (l + r) >> 1;
lson[rt] = build(l,mid);
rson[rt] = build(mid + 1,r);
}
return rt;
}
int update(int rt,int pos,int val){
int newrt = tot ++,tmp = newrt;
C[newrt] = C[rt] + val;
int l = 1,r = n;
while(l < r){
int mid = (l + r) >> 1;
if(pos <= mid){
lson[newrt] = tot ++;
rson[newrt] = rson[rt];
newrt = lson[newrt];
rt = lson[rt];
r = mid;
}
else {
rson[newrt] = tot ++;
lson[newrt] = lson[rt];
newrt = rson[newrt];
rt = rson[rt];
l = mid + 1;
}
C[newrt] = C[rt] + val;
}
return tmp;
}
int query(int l,int r,int ql,int qr,int i){
if(ql <= l && r <= qr)
return C[i];
int mid = (l + r) >> 1;
int ans = 0;
if(ql <= mid) ans += query(l,mid,ql,qr,lson[i]);
if(qr > mid) ans += query(mid + 1,r,ql,qr,rson[i]);
return ans;
}
int main() {
scanf("%d",&n); build(1,n);
for(int i = 1;i <= n;++ i){
int x; scanf("%d",&x);
if(pos[x]){
T[i] = update(T[i - 1],pos[x],-1);
T[i] = update(T[i],i,1);
}
else {
T[i] = update(T[i - 1],i,1);
}
pos[x] = i;
}
int q; scanf("%d",&q);
while(q --){
int l,r; scanf("%d%d",&l,&r);
printf("%d\n",query(1,n,l,r,T[r]));
}
return 0;
}