-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdquery_using_mo's_algo_spoj.cpp
94 lines (69 loc) · 1.55 KB
/
dquery_using_mo's_algo_spoj.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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
#include<bits/stdc++.h>
using namespace std;
const int N = 2e5+2, MOD = 1e9+7;
struct Q {
int l, r, idx;
};
int rootN;
Q q[N];
bool compare(Q q1, Q q2) {
if(q1.l/rootN == q2.l/rootN)
return q1.r > q2.r;
return q1.l < q2.l;
}
int main() {
int n;
cin>>n;
vector<int> a(n);
for(int i=0; i<n; i++)
cin>>a[i];
rootN = sqrtl(n);
int queries;
cin>>queries;
for(int i=0; i<queries; i++) {
int l, r;
cin>>l>>r;
q[i].l = l;
q[i].r = r;
q[i].idx = i;
}
sort(q, q+queries, compare);
vector<int> ans(queries);
int curr_l = 0, curr_r = -1, l, r;
int curr_ans = 0;
vector<int> freq(10*N, 0);
for(int i=0; i<queries; i++) {
l = q[i].l;
r = q[i].r;
l--;
r--;
while(curr_r < r) {
curr_r++;
freq[a[curr_r]]++;
if(freq[a[curr_r]] == 1)
curr_ans++;
}
while(curr_l > l) {
curr_l--;
freq[a[curr_l]]++;
if(freq[a[curr_l]] == 1)
curr_ans++;
}
while(curr_l < l) {
freq[a[curr_l]]--;
if(freq[a[curr_l]] == 0)
curr_ans--;
curr_l++;
}
while(curr_r > r) {
freq[a[curr_r]]--;
if(freq[a[curr_r]] == 0)
curr_ans--;
curr_r--;
}
ans[q[i].idx] = curr_ans;
}
for(int i=0; i<queries; i++)
cout<<ans[i]<<endl;
return 0;
}