-
Notifications
You must be signed in to change notification settings - Fork 174
/
Copy pathDistinct Values Queries.cpp
59 lines (49 loc) · 1.18 KB
/
Distinct Values Queries.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
#include <bits/stdc++.h>
using namespace std;
typedef array<int,3> triple;
const int maxN = 2e5+1;
int N, Q, a, b, x[maxN], ptr[maxN], ds[maxN], ans[maxN];
triple queries[maxN];
map<int,int> mp;
set<int> S;
void update(int idx, int val){
for(int i = idx; i <= N; i += -i&i)
ds[i] += val;
}
int query(int idx){
int sum = 0;
for(int i = idx; i > 0; i -= -i&i)
sum += ds[i];
return sum;
}
int main(){
scanf("%d %d", &N, &Q);
for(int i = 1; i <= N; i++)
scanf("%d", &x[i]);
for(int i = N; i > 0; i--){
if(mp[x[i]])
ptr[i] = mp[x[i]];
mp[x[i]] = i;
}
for(int i = 1; i <= N; i++){
if(S.count(x[i]) == 0)
update(i, 1);
S.insert(x[i]);
}
for(int i = 0; i < Q; i++){
scanf("%d %d", &a, &b);
queries[i] = {a, b, i};
}
sort(queries, queries+Q);
int l = 1;
for(int q = 0; q < Q; q++){
while(l < queries[q][0]){
if(ptr[l])
update(ptr[l], 1);
l++;
}
ans[queries[q][2]] = query(queries[q][1]) - query(queries[q][0]-1);
}
for(int q = 0; q < Q; q++)
printf("%d\n", ans[q]);
}