题面:https://codefun2000.com/p/P1434
#include "bits/stdc++.h"
using namespace std;
using ll = long long;
struct Node1
{
ll weight;
unordered_set<Node1*> neibors;
};
const int N = 1e5 + 5;
ll ans = 0, sum = 0;
void dfs(Node1* cur, Node1* father, int curdepth)
{
sum += curdepth * cur->weight; // 累加所有结点权重值之和
for (auto child : cur->neibors)
{
if (child == father)
continue;
dfs(child, cur, curdepth + 1);
cur->weight += child->weight;
}
// curdepth - 2 为深度减少的大小(无脑接到根节点上)
// 取max:记录能减少的最大的量
ans = max(ans, cur->weight * (curdepth - 2));
}
int main()
{
int n;
cin >> n;
unordered_map<int, Node1*> nodes;
nodes[0] = new Node1;
for (int i = 1; i <= n; ++i)
{
nodes[i] = new Node1;
cin >> nodes[i]->weight;
}
int x, y;
for (int i = 1; i < n; ++i)
{
cin >> x >> y;
nodes[x]->neibors.insert(nodes[y]);
nodes[y]->neibors.insert(nodes[x]);
}
dfs(nodes[1], nodes[0], 1);
cout << sum - ans;
return 0;
}