Luogu P5268 [SNOI2017]一个简单的询问

题目描述

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

Solution

我们利用容斥将答案拆成 $(1,r_1)(1,r_2)-(1,r_1)(1,l_2)-(1,l_1)(1,r_2)+(1,l_1)(1,l_2)$ 的形式

然后用莫队即可

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
#include <iostream>
#include <cstdio>
#include <cmath>
#include <algorithm>
#define maxn 50010
#define ll long long
using namespace std;

int n, m, k, a[maxn];

int blo, c1;
struct Query {
int l, r, k, 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[4 * maxn];

int cnt[maxn][2]; ll ans, Ans[maxn];
inline void add(int v, int T) {
++cnt[v][T]; ans += cnt[v][T ^ 1];
}

inline void del(int v, int T) {
--cnt[v][T]; ans -= cnt[v][T ^ 1];
}

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

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