P4438 [HNOI/AHOI2018] 道路 题解
注意到树高度不超过 ,我们考虑有没有什么可以突破的地方。
我们要求的答案也是与路径中的边数有关,不妨考虑 DP, 表示从根到 经过了 条未翻修的公路和 条未翻修的铁路,考虑以 为根的子树的最小答案。转移考虑选的是左儿子翻修还是右儿子翻修即可。注意到这个东西顺推可能有点难写,考虑写个记忆化。令 为树最高高度,复杂度 ,,可以通过。
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cmath>
#include <cstring>
#include <string>
#include <vector>
using namespace std;
const int N = 4e4 + 5;
int n;
int s1[N], s2[N];
long long f[N][41][41];
long long a[N], b[N], c[N];
vector<int> G[N];
int main()
{
ios::sync_with_stdio(0), cin.tie(0);
cin >> n;
for (int i = 1; i < n; i++)
{
int s, t;
cin >> s >> t;
if (s < 0) s = (-s) + n - 1;
if (t < 0) t = (-t) + n - 1;
s1[i] = s, s2[i] = t;
}
for (int i = n; i <= 2 * n - 1; i++) cin >> a[i] >> b[i] >> c[i];
auto dfs = [&](auto self, int u, int x, int y)->long long
{
if (f[u][x][y]) return f[u][x][y];
if (u > n - 1)
{
return c[u] * (a[u] + x) * (b[u] + y);
}
// think of left or right
// left
long long res = self(self, s1[u], x, y) + self(self, s2[u], x, y + 1);
long long res2 = self(self, s1[u], x + 1, y) + self(self, s2[u], x, y);
return f[u][x][y] = min(res, res2);
};
cout << dfs(dfs, 1, 0, 0) << "\n";
return 0;
}

浙公网安备 33010602011771号