题面
Sol
给定\(N\)个正整数构成的序列,将对于指定的闭区间查询其区间内的不同的数的个数
主席树
不是权值线段树
维护位置
如果插入一个数时发现之前有过了
那么修改当前的,那个位置\(-1\)
然后插入这个数字,在相应的位置\(+1\)
# include <bits/stdc++.h>
# define RG register
# define IL inline
# define Fill(a, b) memset(a, b, sizeof(a))
using namespace std;
typedef long long ll;
const int _(3e4 + 5);
const int __(1e6);
IL int Input(){
RG int x = 0, z = 1; RG char c = getchar();
for(; c < '0' || c > '9'; c = getchar()) z = c == '-' ? -1 : 1;
for(; c >= '0' && c <= '9'; c = getchar()) x = (x << 1) + (x << 3) + (c ^ 48);
return x * z;
}
int n, m, rt[_], tot, o[_], len, a[_], vis[_];
struct HJT{
int ls, rs, sz;
} T[__];
IL void Modify(RG int &x, RG int l, RG int r, RG int p, RG int v){
T[++tot] = T[x], T[x = tot].sz += v;
if(l == r) return;
RG int mid = (l + r) >> 1;
if(p <= mid) Modify(T[x].ls, l, mid, p, v);
else Modify(T[x].rs, mid + 1, r, p, v);
}
IL int Query(RG int x, RG int l, RG int r, RG int L, RG int R){
if(!x) return 0;
if(L <= l && R >= r) return T[x].sz;
RG int mid = (l + r) >> 1, ret = 0;
if(L <= mid) ret = Query(T[x].ls, l, mid, L, R);
if(R > mid) ret += Query(T[x].rs, mid + 1, r, L, R);
return ret;
}
int main(RG int argc, RG char* argv[]){
n = Input();
for(RG int i = 1; i <= n; ++i) o[i] = a[i] = Input();
sort(o + 1, o + n + 1), len = unique(o + 1, o + n + 1) - o - 1;
for(RG int i = 1; i <= n; ++i){
a[i] = lower_bound(o + 1, o + len + 1, a[i]) - o;
rt[i] = rt[i - 1];
if(!vis[a[i]]) vis[a[i]] = i, Modify(rt[i], 1, n, i, 1);
else{
Modify(rt[i], 1, n, vis[a[i]], -1);
vis[a[i]] = i;
Modify(rt[i], 1, n, i, 1);
}
}
m = Input();
for(RG int i = 1; i <= m; ++i){
RG int l = Input(), r = Input();
printf("%d\n", Query(rt[r], 1, n, l, r));
}
return 0;
}