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
| // 더 많은 정보는 42jerrykim.github.io 에서 확인하세요.
#include <bits/stdc++.h>
using namespace std;
struct FastScanner {
static const int BUFSIZE = 1 << 20;
int idx, size;
char buf[BUFSIZE];
FastScanner() : idx(0), size(0) {}
inline char read() {
if (idx >= size) {
size = (int)fread(buf, 1, BUFSIZE, stdin);
idx = 0;
if (size == 0) return 0;
}
return buf[idx++];
}
template <typename T>
bool nextInt(T &out) {
char c = read();
if (c == 0) return false;
while (c != '-' && (c < '0' || c > '9')) {
c = read();
if (c == 0) return false;
}
T sign = 1;
if (c == '-') {
sign = -1;
c = read();
}
T num = 0;
for (; c >= '0' && c <= '9'; c = read()) num = num * 10 + (c - '0');
out = num * sign;
return true;
}
};
struct Fenwick {
int n;
vector<int> t;
Fenwick(int n = 0) : n(n), t(n + 1, 0) {}
inline void add(int i, int v) { for (; i <= n; i += i & -i) t[i] += v; }
inline int sum(int i) const { int r = 0; for (; i > 0; i -= i & -i) r += t[i]; return r; }
};
struct Query { int l, r, id; };
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
FastScanner fs;
int N; if (!fs.nextInt(N)) return 0;
vector<int> a(N + 1);
for (int i = 1; i <= N; ++i) fs.nextInt(a[i]);
int Q; fs.nextInt(Q);
vector<Query> qs(Q);
for (int i = 0; i < Q; ++i) { fs.nextInt(qs[i].l); fs.nextInt(qs[i].r); qs[i].id = i; }
// 좌표 압축
vector<int> comp(N);
for (int i = 1; i <= N; ++i) comp[i - 1] = a[i];
sort(comp.begin(), comp.end());
comp.erase(unique(comp.begin(), comp.end()), comp.end());
for (int i = 1; i <= N; ++i) a[i] = int(lower_bound(comp.begin(), comp.end(), a[i]) - comp.begin()) + 1;
int M = (int)comp.size();
// r 오름차순 정렬
sort(qs.begin(), qs.end(), [](const Query &x, const Query &y){ return x.r < y.r; });
Fenwick bit(N);
vector<int> lastOcc(M + 2, 0);
vector<int> ans(Q);
int curR = 0;
for (const auto &q : qs) {
while (curR < q.r) {
++curR;
int v = a[curR];
int prev = lastOcc[v];
if (prev) bit.add(prev, -1);
bit.add(curR, +1);
lastOcc[v] = curR;
}
ans[q.id] = bit.sum(q.r) - bit.sum(q.l - 1);
}
for (int i = 0; i < Q; ++i) cout << ans[i] << '\n';
return 0;
}
|