首先,对于 的情况可以直接特判。对于 的情况,我们钦定一个度数大于 的点为根。
由于是树上链加,所以考虑差分。那么对于一次操作,即可转化为两个叶子节点 , 和 父节点处 。
设 表示节点 的差分值, 表示节点 需要作为 操作几次, 表示 子树内叶子节点仍然可以增加的值。
对于叶子节点显然 。
对于非叶子节点的 有 , 因为对于 本身原本需要减去的值为 ,但是它作为 的父亲被减去的值为 。 对于非叶子节点的 有 。
现在考虑如何判定是否存在解。
首先需要满足对于所有的 ,都有 即操作次数非负,这个显然。
其次需要满足 ,即所有的叶子的值都被加完。
最后重点需要考虑的是对于点 如何选择子树内的点进行两两配出 对。 容易发现,若一个操作的 是 ,那么选择的两个叶子一定在 的两个不同儿子的子树内。那么当前点的 能被满足当且仅当 。
证明: 设 ,如果 ,那么显然只能够取到 。否则,类比 WC2023 T2,将子树内的叶子放在序列上,第 次取 和 配对即可。显然总对数不可能超过 。
#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;
}