codeforces
给出一棵树,每个点有权值,每次操作可以对一个联通子集中的点全部加1,或者全部减1,且每次操作必须包含点1,问最少通过多少次操作可以让整棵树每个点的权值变为0.
#include
#include
#include
#include
#include
#include
#define MAX 100007
using namespace std;
typedef long long LL;
int n,u,v;
LL up[MAX],down[MAX],a[MAX];
vector<int> e[MAX];
void dfs ( int u , int p )
{
up[u] = down[u] = 0;
for ( int i = 0 ; i < e[u].size() ; i++ )
{
int v = e[u][i];
if ( v == p ) continue;
dfs ( v , u );
up[u] = max ( up[u] , up[v] );
down[u] = max ( down[u] , down[v] );
}
a[u] += up[u]-down[u];
if ( a[u] > 0 ) down[u] += a[u];
else up[u] -= a[u];
}
void add ( int u , int v )
{
e[u].push_back ( v );
e[v].push_back ( u );
}
int main ()
{
while (~scanf ( "%d" , &n ))
{
for ( int i = 0 ; i < MAX ; i++ )
e[i].clear();
for ( int i = 1 ; i < n ; i++ )
{
scanf ( "%d%d" , &u , &v );
add ( u , v );
}
for ( int i = 1 ; i <= n ; i++ )
scanf ( "%I64d" , &a[i] );
dfs ( 1 , -1 );
printf ( "%I64d\n" , up[1]+down[1] );
}
}