题意:有n个点,每个点有相应的人数,n-1条带权边,从a点的所有人走到b点的花费是a点的人数*边权值,问所有人在哪个点集合能够使花费最小求最小花费。
思路:
先dfs求出以1为根节点使每个点后代到这个点集合的花费sum以及这个点及其后代共有几个人cnt
然后枚举每个点i作为集合点(根节点)时他的花费就是sum[i]+他的父节点减去从i来的人的花费+父节点总人数减去从i来的人数*边权
值。并且更新最小花费和sum[i],cnt[i].
代码:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<vector>
using namespace std;
typedef long long ll;
const int maxn = 2e5+5;
const int INF = 0x3f3f3f3f;
int n, v[maxn], cnt[maxn];
ll sum[maxn], ans;
struct node
{
int v, w;
node() {}
node(int vv, int ww): v(vv), w(ww) {}
};
vector<node> g[maxn];
void dfs(int x, int fa)
{
cnt[x] = v[x]; sum[x] = 0;
for(int i = 0; i < g[x].size(); i++)
{
int to = g[x][i].v;
int w = g[x][i].w;
if(to == fa) continue;
dfs(to, x);
cnt[x] += cnt[to];
sum[x] += (sum[to]+(ll)cnt[to]*w);
}
}
void dfs1(int x, int fa)
{
for(int i = 0; i < g[x].size(); i++)
{
int to = g[x][i].v;
int w = g[x][i].w;
if(to == fa) continue;
sum[to] = sum[to]+(sum[x]-sum[to]-(ll)cnt[to]*w)+(ll)(cnt[x]-cnt[to])*w;
cnt[to] += (cnt[x]-cnt[to]);
ans = min(ans, sum[to]);
dfs1(to, x);
}
}
int main(void)
{
while(cin >> n)
{
memset(sum, 0, sizeof(sum));
for(int i = 0; i < maxn; i++)
g[i].clear();
for(int i = 1; i <= n; i++)
scanf("%d", &v[i]);
for(int i = 1; i < n; i++)
{
int u, v, w;
scanf("%d%d%d", &u, &v, &w);
g[u].push_back(node(v, w));
g[v].push_back(node(u, w));
}
dfs(1, 0);
ans = sum[1];
dfs1(1, 0);
printf("%lld\n", ans);
}
return 0;
}