AGC010C
首先,对于
由于是树上链加,所以考虑差分。那么对于一次操作,即可转化为两个叶子节点
设
对于叶子节点显然
对于非叶子节点的
现在考虑如何判定是否存在解。
首先需要满足对于所有的
其次需要满足
最后重点需要考虑的是对于点
证明:
设
#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;
}