这是由 AI 翻译为中文文本的官方题解
子任务 1
漂流的次数至多为 次。因为在进行 次漂流结束时,城市 的灯光强度将变为 ,从而能够照亮所有的城市。当进行 次以上、 次以下的漂流时,注意到漂流的顺序可以忽略,需要检查的方案数为 种。当 时为 种方案,这是可以通过全搜索(暴力枚举)解决的。因此,只需对每种情况模拟并验证是否所有城市都被实际照亮即可。时间复杂度为 等。
子任务 3
在这个子任务中,至多进行 次漂流即可满足条件。此外,即使进行了 次漂流,也可以假设这两次漂流结束的城市是同一个。
如果在城市 结束漂流,需要的次数为 次,此时的代价为 。如果在城市 ()结束漂流,需要的次数在 时为 次,代价为 ;在 时为 次,代价为 。取这些情况中的最小值即为答案。
子任务 4
在这个子任务中,同样可以假设所有漂流结束的城市都是同一个。当在城市 结束漂流时,需要的次数为 次,代价为 。取这些情况中的最小值即为答案。
子任务 2
考虑以下的 dp(动态规划):
以城市 为根的子树中,进行 次漂流,且未被照亮的城市到 的最大深度为 时的最小代价
设城市 的子孙节点中 的最小值为 。并设城市 的子节点为 。此时 可以通过以下状态转移方程求得:
这里,最终答案为 。dp 数组的大小为 ,状态转移通过使用累积 (前缀最小值)可以在 内完成,因此时间复杂度为 。
子任务 5,满分
设城市 的子树中最远城市到 的深度为 。此时 dp 数组中需要计算的仅有 且 的部分。因此,dp 数组只需计算这部分即可。所以,对于具有子节点 的城市 ,其状态转移所需的时间复杂度为 。由于 ,基于与平方树 DP(树上背包)相同的理由,对整体求和后的总时间复杂度为 ,因此这个问题可以在 时间内解决。另外请注意,最坏情况下的时间复杂度也是 。如果子节点的数量在 个及以上,只需每次将 个子节点进行合并即可。
提供的参考代码:
#include <algorithm>
#include <cstdint>
#include <cstdio>
#include <vector>
using i64 = std::int64_t;
const i64 INF = 1e18;
template <typename T>
void chmax(T &a, const T &b) {
a = std::max(a, b);
}
template <typename T>
void chmin(T &a, const T &b) {
a = std::min(a, b);
}
int main() {
int N;
scanf("%d", &N);
std::vector<std::vector<int>> edges(N);
for (int i = 1; i <= N - 1; i++) {
int p;
scanf("%d", &p);
edges[i].push_back(p - 1);
edges[p - 1].push_back(i);
}
std::vector<i64> C(N);
for (int i = 0; i < N; i++) {
scanf("%ld", &C[i]);
}
std::vector<int> height(N);
auto merge = [&](const std::vector<std::vector<i64>> &a, const std::vector<std::vector<i64>> &b) -> std::vector<std::vector<i64>> {
int a_max = a.size() - 1;
int b_max = b.size() - 1;
int res_max = std::max(a_max, b_max);
std::vector res(res_max + 1, std::vector<i64>(res_max + 1, INF));
for (int i = 0; i <= a_max; i++) {
for (int j = 0; j <= b_max; j++) {
if (i + j > res_max) {
continue;
}
i64 min_a = INF, min_b = INF;
for (int k = 0; k <= res_max; k++) {
if (k <= a_max) {
chmin(min_a, a[i][k]);
}
if (k <= b_max) {
chmin(min_b, b[j][k]);
}
chmin(res[i + j][k], min_a + min_b);
}
}
}
return res;
};
auto dfs = [&](auto self, int v, int p) -> std::vector<std::vector<i64>> {
height[v] = 0;
std::vector res(1, std::vector(1, INF));
res[0][0] = 0;
for (int w : edges[v]) {
if (w == p) continue;
auto sub_dp = self(self, w, v);
res = merge(res, sub_dp);
chmax(height[v], height[w] + 1);
chmin(C[v], C[w]);
}
res.resize(height[v] + 2);
for (int i = 0; i <= height[v] + 1; i++) {
res[i].resize(height[v] + 2, INF);
for (int j = height[v]; j >= 0; j--) {
res[i][j + 1] = res[i][j];
}
res[i][0] = INF;
}
for (int i = 0; i <= height[v] + 1; i++) {
for (int j = 0; j <= height[v] + 1; j++) {
chmin(res[j][0], res[i][j] + C[v] * std::max(0, j - i));
}
}
return res;
};
auto dp = dfs(dfs, 0, -1);
i64 ans = INF;
for (auto &v: dp) {
chmin(ans, v[0]);
}
printf("%ld\n", ans);
}