SP3267 DQUERY - D-query

题目描述

https://www.luogu.com.cn/problem/SP3267

Solution

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
#include <iostream>
#include <cstdio>
#include <cmath>
#include <algorithm>
#define maxn 30010
#define maxs 1000010
#define maxm 200010
using namespace std;

int n, m, a[maxn];

int blo, ans[maxm];
struct Query {
int l, r, id;

friend bool operator < (const Query &u, const Query &v) {
if (u.l / blo == v.l / blo) return u.l / blo & 1 ? u.r < v.r : u.r > v.r;
return u.l < v.l;
}
} Q[maxm];

int cnt[maxs], Ans;
inline void add(int v) {
if (++cnt[v] == 1) ++Ans;
}

inline void del(int v) {
if (--cnt[v] == 0) --Ans;
}

int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr); cout.tie(nullptr);

cin >> n;
for (int i = 1; i <= n; ++i) cin >> a[i];
cin >> m; blo = n / sqrt(m);
for (int i = 1; i <= m; ++i) cin >> Q[i].l >> Q[i].r, Q[i].id = i;
sort(Q + 1, Q + m + 1);
int l = Q[1].l, r = l - 1;
for (int i = 1; i <= m; ++i) {
while (r < Q[i].r) add(a[++r]);
while (l > Q[i].l) add(a[--l]);
while (r > Q[i].r) del(a[r--]);
while (l < Q[i].l) del(a[l++]);
ans[Q[i].id] = Ans;
}
for (int i = 1; i <= m; ++i) cout << ans[i] << "\n";
return 0;
}