主体思路:树形 DP
复杂度:
完整思路
首先转化题意,相当于对于每个边选定其方向,然后合并合法路径减小总代价。
考虑没有 情况,也就是说相邻点对的大小关系是固定的。此时对于任意边 ,都钦定方向 是最优的。(或者都钦定为 ,这两种方式等价,此题解中采用 。)此时一个点 贡献的代价 为 ,其中 分别表示其入度和出度。总代价即所有点代价之和。
重新考虑原问题,我们设 表示节点 子树内,在 这条边被钦定为向上/向下的最小代价。假设现在正在处理节点 ,对于 的子节点 的贡献是固定的,我们只需要考虑 的贡献。我们先钦定这些边都是向上的,即 ,接下来的问题就是从这些子节点中挑一些将其钦定为 ,使得总代价最小。调整一个点对于 的数量贡献是固定的,于是我们贪心地优先调整 较小的点。
考虑记录所有的 的 ,将其按照 从小到大排序,每次调整贡献并尝试更新。
特别地,考虑 使 的出度加一, 使 的入度加一,这考虑的是边 被钦定的方向,如果 ,那么 状态中只有一个会被使用。
设 表示 的子树, 表示被钦定为 的点 的集合, 表示被钦定为 的点 的集合(向上/向下连边的两个子节点集合),于是有以下形式化的转移:
以上式子中的 表示以 为根进行 DP 时,其没有父节点,也就不存在与父节点连边的那个度数。
代码实现需要注意的地方:
- 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;
}