1827: [Usaco2010 Mar]gather 奶牛大集会
Description
Bessie正在计划一年一度的奶牛大集会,来自全国各地的奶牛将来参加这一次集会。当然,她会选择最方便的地点来举办这次集会。每个奶牛居住在 N(1<=N<=100,000) 个农场中的一个,这些农场由N-1条道路连接,并且从任意一个农场都能够到达另外一个农场。道路i连接农场A_i和B_i(1 <= A_i <=N; 1 <= B_i <= N),长度为L_i(1 <= L_i <= 1,000)。集会可以在N个农场中的任意一个举行。另外,每个牛棚中居住者C_i(0 <= C_i <= 1,000)只奶牛。在选择集会的地点的时候,Bessie希望最大化方便的程度(也就是最小化不方便程度)。比如选择第X个农场作为集会地点,它的不方便程度是其它牛棚中每只奶牛去参加集会所走的路程之和,(比如,农场i到达农场X的距离是20,那么总路程就是C_i*20)。帮助Bessie找出最方便的地点来举行大集会。 考虑一个由五个农场组成的国家,分别由长度各异的道路连接起来。在所有农场中,3号和4号没有奶牛居住。
Input
第一行:一个整数N * 第二到N+1行:第i+1行有一个整数C_i * 第N+2行到2*N行,第i+N+1行为3个整数:A_i,B_i和L_i。
Output
- 第一行:一个值,表示最小的不方便值。
Sample Input
5
1
1
0
0
2
1 3 1
2 3 2
3 4 3
4 5 3
Sample Output
15
题解
考虑在点(x)处的答案为(ans),总奶牛数为(tot),i为根子树总奶牛数为(size_i),对于(x)的一个儿子(y)的答案为(ans^{'}),(y)到(x)边权为(w)
有
[ans^{'} = ans - size_i imes w + (tot - size_i) * w
]
化简得
[ans^{'} = ans + (tot - 2 imes size_i) * w
]
即(tot - 2 imes size_i < 0)时t比x优
从根跑下来找到最优点然后以它为起点(dfs)/(bfs)一遍就行了。。