AGC010C

· · 题解

首先,对于 n = 2 的情况可以直接特判。对于 n > 2 的情况,我们钦定一个度数大于 2 的点为根。

由于是树上链加,所以考虑差分。那么对于一次操作,即可转化为两个叶子节点 +1,lca 和 lca 父节点处 -1。

设 d_u 表示节点 u 的差分值,c_u 表示节点 u 需要作为 lca 操作几次,f_u 表示 u 子树内叶子节点仍然可以增加的值。

对于叶子节点显然 c_u = 0, \ f_u = a_u。

对于非叶子节点的 c_u 有 c_u = -d_u - \sum_{v \in son_v} c_v, 因为对于 u 本身原本需要减去的值为 -d_u,但是它作为 lca 的父亲被减去的值为 \sum_{v \in son_v} c_v。 对于非叶子节点的 f_u 有 f_u = (\sum_{v \in son_u}f_v) - 2c_u。

现在考虑如何判定是否存在解。

首先需要满足对于所有的 u,都有 c_u \geq 0 即操作次数非负,这个显然。

其次需要满足 f_{root} = 0,即所有的叶子的值都被加完。

最后重点需要考虑的是对于点 u 如何选择子树内的点进行两两配出 c_u 对。 容易发现,若一个操作的 lca 是 u,那么选择的两个叶子一定在 u 的两个不同儿子的子树内。那么当前点的 c_u 能被满足当且仅当 c_u \leq \min\{f_u - \max_{v \in son_u}\{f_v\}, \frac{f_u}{2}\}。

证明: 设 maxv = \max_{v \in son_u}\{f_v\},如果 maxv > \frac{f_u}{2},那么显然只能够取到 f_u - maxv。否则,类比 WC2023 T2,将子树内的叶子放在序列上,第 i 次取 i 和 \frac{f_u}{2} + i 配对即可。显然总对数不可能超过 \frac{f_u}{2}。

#include<bits/stdc++.h>
using namespace std;

inline int read() {
    int res = 0, f = 1; char ch;
    while((ch = getchar()) && (ch < '0' || ch > '9') && ch != '-');
    (ch == '-') ? f = -1 : res = ch - '0';
    while((ch = getchar()) && ch >= '0' && ch <= '9') res = (res << 3) + (res << 1) + ch - '0';
    return res * f;
}

const int MAXN = 1e5 + 5;

int rt, n, a[MAXN], du[MAXN], d[MAXN], c[MAXN], f[MAXN];
int tot, hd[MAXN], to[MAXN << 1], nt[MAXN << 1];

inline void add(int x, int y) {
    ++du[x]; ++du[y];
    to[++tot] = y, nt[tot] = hd[x], hd[x] = tot;
    to[++tot] = x, nt[tot] = hd[y], hd[y] = tot;
}

void dfs(int now, int fa) {
    d[now] = a[now];
    if(du[now] == 1) return f[now] = a[now], void();
    for(int i = hd[now]; i; i = nt[i])
     if(to[i] != fa) d[now] -= a[to[i]], dfs(to[i], now), c[now] -= c[to[i]];
    c[now] -= d[now];
    if(c[now] < 0) { puts("NO"); exit(0); }
    int sum = 0, mx = 0;
    for(int i = hd[now]; i; i = nt[i])
     if(to[i] != fa) sum += f[to[i]], mx = max(mx, f[to[i]]);
    int lim = min(sum / 2, sum - mx);
    if(lim < c[now]) { puts("NO"); exit(0); }
    f[now] = sum - 2 * c[now];
}

int main() {
    n = read();
    for(int i = 1; i <= n; i++) a[i] = read();
    if(n == 2) return puts((a[1] == a[2]) ? "YES" : "NO"), 0;
    for(int i = 1, x, y; i < n; i++) {
        x = read(); y = read();
        add(x, y);
    }
    int rt = 1;
    for(int i = 1; i <= n; i++)
     if(du[i] > 1) { rt = i; break; }
    dfs(rt, 0);
    puts(f[rt] == 0 ? "YES" : "NO");
    return 0;
}