CF1394D Boboniu and Jianghu【题解】
\color{blueviolet}\text{CF 杂题集(点我)}
\color{red}\text{博客内食用效果更佳(点我)}
主体思路:树形 DP
复杂度:O(n \log n)
完整思路
首先转化题意,相当于对于每个边选定其方向,然后合并合法路径减小总代价。
考虑没有
重新考虑原问题,我们设
考虑记录所有的
特别地,考虑
设
以上式子中的
代码实现需要注意的地方:
- DP 数组需要开 long long。
参考代码:
#pragma GCC optimize(2)
#pragma GCC optimize(3)
#pragma GCC optimize("Ofast")
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef unsigned long long ULL;
typedef unsigned int UIT;
typedef double DB;
typedef pair<int, int> PII;
#define fi first
#define se second
//--------------------//
const int N = 2e5 + 5, M = 4e5 + 5;
int n, a[N], b[N];
struct Edge {
int to, nex;
} edge[M];
int tot, head[N];
void add(int from, int to) {
edge[++tot] = {to, head[from]};
head[from] = tot;
}
LL f[N][2];
bool cmp(int x, int y) {
return f[x][1] - f[x][0] < f[y][1] - f[y][0];
}
int tcnt, tem[N];
void DFS(int now, int fa) {
for (int to, i = head[now]; i; i = edge[i].nex) {
to = edge[i].to;
if (to != fa)
DFS(to, now);
}
int cnt0 = 0, cnt1 = 0; LL sum = 0; tcnt = 0;
for (int to, i = head[now]; i; i = edge[i].nex) {
to = edge[i].to;
if (to == fa)
continue;
if (b[to] < b[now])
cnt0++, sum += f[to][0];
else if (b[to] > b[now])
cnt1++, sum += f[to][1];
else
cnt0++, sum += f[to][0], tem[++tcnt] = to; // 存特殊节点
}
sort(tem + 1, tem + tcnt + 1, cmp); // 按照代价从小到大排序
f[now][0] = sum + 1LL * max(cnt0, cnt1 + (fa != 0)) * a[now];
f[now][1] = sum + 1LL * max(cnt0 + (fa != 0), cnt1) * a[now];
for (int to, i = 1; i <= tcnt; i++) {
to = tem[i], sum += f[to][1] - f[to][0], cnt0--, cnt1++;
f[now][0] = min(f[now][0], sum + 1LL * max(cnt0, cnt1 + (fa != 0)) * a[now]);
f[now][1] = min(f[now][1], sum + 1LL * max(cnt0 + (fa != 0), cnt1) * a[now]);
}
}
//--------------------//
int main() {
scanf("%d", &n);
for (int i = 1; i <= n; i++)
scanf("%d", &a[i]);
for (int i = 1; i <= n; i++)
scanf("%d", &b[i]);
for (int u, v, i = 1; i < n; i++)
scanf("%d%d", &u, &v), add(u, v), add(v, u);
DFS(1, 0);
printf("%lld", f[1][0]);
// f[1][0] 一定与 f[1][1] 相等,输出哪一个都行
return 0;
}