icpc2025网络赛1

· · 题解

D

分析

>> 题目意思

给定一个树,每个点有一个点权。

把树分成若干连通块,对于每一个连通块计算连通块内节点点权的最大值和最小值的差值,使各个连通块计算值的和最大。

求这个最大值。

>> 特殊性质

我们发现把树分成多条严格单调的链是最优的。

证明链:

证明点单调:

>> 树形dp

代码实现

#include <bits/stdc++.h>
using namespace std;
using i64 = long long;
const int N = 1e6 + 10;
const int inf = 0x3f3f3f3f;
int head[N], nxt[N << 1], ver[N << 1], edge[N << 1], a[N];
int n, tot;
i64 f[N][3], mx[N];
void add(int x, int y) {
    ver[++tot] = y, nxt[tot] = head[x], head[x] = tot;
}
void dfs(int x, int fa) {
    f[x][0] = f[x][1] = f[x][2] = 0;
    int l = 0, s = 0;
    i64 sum = 0;
    for (int i = head[x]; i; i = nxt[i]) {
        int y = ver[i];
        if (y == fa) continue;
        dfs(y, x);
        sum += mx[y];
    }
    f[x][0] = f[x][1] = f[x][2] = sum;
    for (int i = head[x]; i; i = nxt[i]) {
        int y = ver[i];
        if (y == fa) continue;
        if (a[y] > a[x]) {
            f[x][1] = max(f[x][1], sum - mx[y] + f[y][1] + a[y] - a[x]);
            if (l == 0 || f[y][1] + a[y] - a[x] - mx[y] > f[l][1] + a[l] - a[x] - mx[l]) l = y;
        } else if (a[y] < a[x]) {
            f[x][2] = max(f[x][2], sum - mx[y] + f[y][2] + a[x] - a[y]);
            if (s == 0 || f[y][2] + a[x] - a[y] - mx[y] > f[s][2] + a[x] - a[s] - mx[s]) s = y;
        }
    }
    if (l && s) {
        f[x][0] = max(f[x][0], sum - mx[l] + f[l][1] - mx[s] + f[s][2] + a[l] - a[s]);
    }
    mx[x] = max(max(f[x][0], f[x][1]), f[x][2]);
}
int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr), cout.tie(nullptr);
    cin >> n;
    for (int i = 1; i <= n; i++) cin >> a[i];
    for (int i = 1; i < n; i++) {
        int x, y;
        cin >> x >> y;
        add(x, y);
        add(y, x);
    }
    dfs(1, 0);
    cout << mx[1] << "\n";
    return 0;
}