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
| // 더 많은 정보는 42jerrykim.github.io 에서 확인하세요.
#include <bits/stdc++.h>
using namespace std;
struct Query {
int l, r, idx, block;
};
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n;
if (!(cin >> n)) return 0;
vector<int> a(n);
for (int i = 0; i < n; ++i) cin >> a[i];
// Coordinate compression
vector<int> comp = a;
sort(comp.begin(), comp.end());
comp.erase(unique(comp.begin(), comp.end()), comp.end());
for (int i = 0; i < n; ++i) {
a[i] = int(lower_bound(comp.begin(), comp.end(), a[i]) - comp.begin());
}
int m = int(comp.size());
int q;
cin >> q;
vector<Query> queries(q);
int blockSize = max(1, int(sqrt(n)));
for (int i = 0; i < q; ++i) {
int l, r;
cin >> l >> r;
--l; --r; // convert to 0-indexed
queries[i] = {l, r, i, l / blockSize};
}
sort(queries.begin(), queries.end(), [&](const Query& A, const Query& B) {
if (A.block != B.block) return A.block < B.block;
if (A.block & 1) return A.r > B.r; // odd-even trick
return A.r < B.r;
});
vector<int> freq(m, 0);
vector<int> ans(q);
int distinct = 0;
auto add = [&](int x) {
if (freq[x] == 0) ++distinct;
++freq[x];
};
auto remove = [&](int x) {
--freq[x];
if (freq[x] == 0) --distinct;
};
int curL = 0, curR = -1; // current range is empty
for (const auto& qu : queries) {
int L = qu.l, R = qu.r;
while (curL > L) add(a[--curL]);
while (curR < R) add(a[++curR]);
while (curL < L) remove(a[curL++]);
while (curR > R) remove(a[curR--]);
ans[qu.idx] = distinct;
}
for (int i = 0; i < q; ++i) {
cout << ans[i] << '\n';
}
return 0;
}
|