经典4 倍增

倍增

给定一个有向图,$n$ 个节点,$n$ 条边(每个点只有一条出边,不一定无环),边权为0或1,询问从每个点出发经过边权为 $0$ 的边的数量或为 $1$ 的数量恰好为 $k$ 时的终点。

如何我们暴力的在图上沿着边走,时间复杂度会达到 $O(nk)$。无法解决问题。

这时我们使用倍增,用 $f(i, j)$ 表示第 $i$ 个节点走 $2^j$ 步后到达的点,用 $g(i,j)$ 表示第 $i$ 个节点走了 $2^j$ 步后经历的边权为 $1$ 的边的数量。 这一步预处理时间复杂度为 $O(nlogk)$ ,这样在处理询问,时间复杂度为 $O(klogk)$ 。总时间复杂度 $O((n + k)logk)$ 。

倍增在处理树上、图上问题往往可以将复杂度由 $O(n)$ 降为 $O(logn)$ ,大大优化时间复杂度。

例题:2024牛客暑期多校第三次场J题

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
#include <bits/stdc++.h>

using i64 = long long;

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

int n, a, b;
std::cin >> n >> a >> b;
std::string s;
std::string ss;
std::cin >> s;
while (ss.size() < 2 * a + n) {
ss += s;
}
int m = ss.size();

std::vector<std::array<int, 18>> f(n + 1);
std::vector<std::array<int, 18>> cnt(n + 1);
int cnt1 = 0, cnt0 = 0;
for (int i = 0, j = -1; i < n; i++) {
while (j < m && cnt1 < a && cnt0 < a) {
j++;
if (ss[j] == '0') {
cnt0++;
} else {
cnt1++;
}
}
f[i + 1][0] = ((j + 1) % n) + 1;
if (cnt1 == a) {
cnt[i + 1][0] = 1;
} else {
cnt[i + 1][0] = 0;
}
if (ss[i] == '0') {
cnt0--;
} else {
cnt1--;
}
}

for (int j = 1; j < 18; j++) {
for (int i = 1; i <= n; i++) {
f[i][j] = f[f[i][j - 1]][j - 1];
cnt[i][j] = cnt[i][j - 1] + cnt[f[i][j - 1]][j - 1];
}
}

std::string ans;
for (int i = 1; i <= n; i++) {
int p = i;
int cnt0 = 0, cnt1 = 0;
for (int j = 17; j >= 0; j--) {
int c1 = cnt[p][j];
int c0 = (1 << j) - c1;
if (cnt0 + c0 < b && cnt1 + c1 < b) {
cnt0 += c0;
cnt1 += c1;
p = f[p][j];
} else if (cnt0 + c0 < b) {
ans += '1';
break;
} else if (cnt1 + c1 < b) {
ans += '0';
break;
}
}
}
std::cout << ans << "\n";
return 0;
}

经典4 倍增
http://example.com/2024/07/26/经典4-倍增/
作者
muxingchengfeng
发布于
2024年7月26日
许可协议