题目翻译请看洛谷
传送门
题目描述
A tree is a graph with n vertices and exactly n - 1 edges; this graph should meet the following condition: there exists exactly one shortest (by number of edges) path between any pair of its vertices.
A subtree of a tree T is a tree with both vertices and edges as subsets of vertices and edges of T.
You're given a tree with n vertices. Consider its vertices numbered with integers from 1 to n. Additionally an integer is written on every vertex of this tree. Initially the integer written on the i-th vertex is equal to vi. In one move you can apply the following operation:
Select the subtree of the given tree that includes the vertex with number 1.
Increase (or decrease) by one all the integers which are written on the vertices of that subtree.
Calculate the minimum number of moves that is required to make all the integers written on the vertices of the given tree equal to zero.
输入格式
The first line of the input contains n (1 ≤ n ≤ 105). Each of the next n - 1 lines contains two integers ai and bi (1 ≤ ai, bi ≤ n; ai ≠ bi) indicating there's an edge between vertices ai and bi. It's guaranteed that the input graph is a tree.
The last line of the input contains a list of n space-separated integers v1, v2, ..., vn (|vi| ≤ 109).
输出格式
Print the minimum number of operations needed to solve the task.
Please, do not write the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
题解。
很简单的一道基础dp,dp[u][0/1]表示u点所要被增减的值,一遍dfs跑出。
#include
#include
#include
#include
#include
#include
using namespace std;
struct zk
{
int u,v,next;
}e[300001];
int head[100001];
long long dp[100001][2],val[100001];
int n,m;
int cnt=0;
void add(int u,int v)
{
e[cnt].u=u;
e[cnt].v=v;
e[cnt].next=head[u];
head[u]=cnt++;
}
void dfs(int u,int fa)
{
for(int i=head[u];i!=-1;i=e[i].next)
{
int v=e[i].v;
if (v==fa) continue;
dfs(v,u);
dp[u][0]=max(dp[u][0],dp[v][0]);
dp[u][1]=max(dp[u][1],dp[v][1]);
}
val[u]=val[u]+dp[u][0]-dp[u][1];
if (val[u]>0) dp[u][1]+=val[u];
else dp[u][0]-=val[u];
}
int main()
{
scanf("%d",&n);
int a,b;
memset(head,-1,sizeof(head));
for(int i=1;i<=n-1;i++)
{
scanf("%d%d",&a,&b);
add(a,b);add(b,a);
}
for(int i=1;i<=n;i++)
{
scanf("%lld",&val[i]);
}
dfs(1,1);
printf("%lld",dp[1][0]+dp[1][1]);
return 0;
}