题目链接:传送门
是这个题的一个变形
就是最小值改成最大值
懒了
直接改了改当时的代码
当时的题解里也有解析
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <complex>
#include <algorithm>
#include <climits>
#define
#define
using namespace std;
struct node {
int next, to; ll dis;
}edge[A];
int head[A], num_edge;
void add_edge(int from, int to, ll dis) {
edge[++num_edge].next = head[from];
edge[num_edge].to = to;
edge[num_edge].dis = dis;
head[from] = num_edge;
}
ll siz[A], dis[A], f[A], ans = -9223372036854775807, sum;
int n, a, b;
void dfs(int fr, int fa) {
for (int i = head[fr]; i; i = edge[i].next) {
int ca = edge[i].to;
if (ca == fa) continue;
dfs(ca, fr);
siz[fr] += siz[ca];
dis[fr] += dis[ca] + edge[i].dis * siz[ca];
}
}
void dd(int fr, int fa) {
ans = max(ans, f[fr]);
for (int i = head[fr]; i; i = edge[i].next) {
int ca = edge[i].to;
if (ca == fa) continue;
f[ca] = f[fr] + (sum - siz[ca]) * edge[i].dis - siz[ca] * edge[i].dis;
dd(ca, fr);
}
}
int main(int argc, const char *argv[]) {
cin >> n;
for (int i = 1; i <= n; i++) cin >> siz[i], sum += siz[i];
for (int i = 1; i < n; i++) {
cin >> a >> b;
add_edge(a, b, 1);
add_edge(b, a, 1);
}
dfs(1, 0); f[1] = dis[1]; dd(1, 0);
if (ans == -9223372036854775807) puts("0");
else cout << ans << endl;
}