1827: [Usaco2010 Mar]gather 奶牛大集會
Time Limit: 1 Sec??Memory Limit: 64 MB Submit: 1129??Solved: 525 [Submit][Status][Discuss]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
1
1
0
0
2
1 3 1
2 3 2
3 4 3
4 5 3
Sample Output
15
先把子樹上所有點移動到根的值計算出來,把移動到1的值設為初始答案,發現如果一個孩子如果更優,那么一定滿足$2*siz>tot$,顯然只可能有一個孩子滿足,那就貪心地移動即可
#include <cstdio> char buf[10000000], *ptr = buf - 1; inline int readint(){int n = 0;char ch = *++ptr;while(ch < '0' || ch > '9') ch = *++ptr;while(ch <= '9' && ch >= '0'){n = (n << 1) + (n << 3) + ch - '0';ch = *++ptr;}return n; } typedef long long ll; const int maxn = 100000 + 10; struct Edge{int to, val, next;Edge(){}Edge(int _t, int _v, int _n): to(_t), val(_v), next(_n){} }e[maxn * 2]; int fir[maxn] = {0}, cnt = 0; inline void ins(int u, int v, int w){e[++cnt] = Edge(v, w, fir[u]); fir[u] = cnt;e[++cnt] = Edge(u, w, fir[v]); fir[v] = cnt; } int c[maxn]; ll f[maxn], siz[maxn], ans; void dfs1(int u, int fa){f[u] = 0;siz[u] = c[u];for(int v, i = fir[u]; i; i = e[i].next){v = e[i].to;if(v == fa) continue;dfs1(v, u);f[u] += f[v] + siz[v] * e[i].val;siz[u] += siz[v];} } void dfs2(int u, int fa){for(int v, i = fir[u]; i; i = e[i].next){v = e[i].to;if(v == fa) continue;if(siz[1] - 2 * siz[v] < 0){ans += (siz[1] - 2 * siz[v]) * e[i].val;dfs2(v, u);}} } int main(){fread(buf, sizeof(char), sizeof(buf), stdin);int N = readint();for(int i = 1; i <= N; i++) c[i] = readint();for(int u, v, w, i = 1; i < N; i++){u = readint();v = readint();w = readint();ins(u, v, w);}dfs1(1, 0);ans = f[1];dfs2(1, 0);printf("%lld\n", ans);return 0; }
?