天天看点

BZOJ 1827: [Usaco2010 Mar]gather 奶牛大集会( dp + dfs )

BZOJ 1827: [Usaco2010 Mar]gather 奶牛大集会( dp + dfs )

选取任意一个点为root , size[ x ] 表示以 x 为根的子树的奶牛数 , dp一次计算出size[ ] && 选 root 为集会地点的不方便程度 . 考虑集会地点由 x 点向它的子节点 son 转移 , 那么以 son 为集会地点比以 x 为集会地点要多 dist( x , son ) * ( tot - size[ x ] ) - dist( x , son ) * size[ x ] = dist( x , son ) * ( tot - 2 * size[ x ] ) ( tot 为奶牛总数 ) , 这样转移就是 O( 1 ) , dfs 一遍 , 并取 min 即为 answer .

-------------------------------------------------------------------------------------

#include<cstdio> #include<cstring> #include<algorithm> #include<iostream>   #define rep( i , n ) for( int i = 0 ; i < n ; i++ ) #define clr( x , c ) memset( x , c , sizeof( x ) )   using namespace std;   typedef long long ll;   const int maxn = 100000 + 5;   struct edge { int to , dist; edge* next; };   edge* head[ maxn ]; edge* pt; edge EDGE[ maxn << 1 ];   void init() { pt = EDGE; clr( head , 0 ); }   void add( int u , int v , int d ) { pt -> to = v; pt -> dist = d; pt -> next = head[ u ]; head[ u ] = pt++; }   #define add_edge( u , v , d ) add( u , v , d ) , add( v , u , d )    int size[ maxn ]; ll ans = 0;   int dp( int x , int fa ) { for( edge* e = head[ x ] ; e ; e = e -> next ) { int to = e -> to; if( to == fa ) continue; dp( to , x ); ans += 1LL * size[ to ] * e -> dist; size[ x ] += size[ to ]; } }   void dfs( int x , int fa , ll res ) { for( edge* e = head[ x ] ; e ; e = e -> next ) { int to = e -> to; if( to == fa ) continue; ll t = res + 1LL * e -> dist * ( size[ 0 ] - size[ to ] * 2 ); ans = min( t , ans ); dfs( to , x , t ); } } int main() { // freopen( "test.in" , "r" , stdin ); init(); int n; cin >> n; rep( i , n )    scanf( "%d" , &size[ i ] );     while( --n ) { int u , v , d; scanf( "%d%d%d" , &u , &v , &d ); --u , --v; add_edge( u , v , d ); } dp( 0 , -1 ); dfs( 0 , -1 , ans ); cout << ans << "\n"; return 0; }

------------------------------------------------------------------------------------- 

1827: [Usaco2010 Mar]gather 奶牛大集会

Time Limit: 1 Sec   Memory Limit: 64 MB

Submit: 747   Solved: 326

[ 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号没有奶牛居住。 

BZOJ 1827: [Usaco2010 Mar]gather 奶牛大集会( dp + dfs )

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

2

1 3 1

2 3 2

3 4 3

4 5 3

Sample Output

15

HINT

Source

Gold

转载于:https://www.cnblogs.com/JSZX11556/p/4558096.html