莫队算法 (咕咕咕)

普通莫队

对于一个离线问题,假如当前已知 `f(x,y)`

并且能 `\mathcal{O}(1)` 的求出 `f(x+1,y),f(x-1,y),f(x,y+1),f(x,y-1)`

就可以考虑使用莫队

被文化课折磨中

期中考完回来更新

(咕咕咕)

例题「Luogu P2709」小 B 的询问

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
#include <math.h>
#include <stdio.h>
#include <algorithm>

const int N = 5e4 + 5;
const int M = 5e4 + 5;
const int K = 5e4 + 5;

int n, m, k, res;
int a[N], ans[M], cnt[K];
int L = 1, R;
int size;

struct Node
{
int l, r, id;
bool friend operator<(Node a, Node b)
{
if (a.l / size != b.l / size)
return a.l < b.l;
return a.r < b.r;
}
} query[M];

void update(int i, int num)
{
if (num == 1)
res += 2 * (++cnt[a[i]]) - 1;
else
res -= 2 * (--cnt[a[i]]) + 1;
}

int main()
{
scanf("%d%d%d", &n, &m, &k);
for (int i = 1; i <= n; i++)
scanf("%d", &a[i]);
size = sqrt(n);
for (int i = 1; i <= m; i++)
scanf("%d%d", &query[i].l, &query[i].r), query[i].id = i;
std::sort(query + 1, query + 1 + m);
for (int i = 1; i <= m; i++)
{
while (query[i].l < L)
update(--L, 1);
while (R < query[i].r)
update(++R, 1);
while (L < query[i].l)
update(L++, -1);
while (query[i].r < R)
update(R--, -1);
ans[query[i].id] = res;
}
for (int i = 1; i <= m; i++)
printf("%d\n", ans[i]);
return 0;
}
# 分块

评论

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×