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 v i. 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.
Input
The first line of the input contains n (1 ≤ n ≤ 105). Each of the next n - 1 lines contains two integers a i and b i (1 ≤ a i, b i ≤ n; a i ≠ b i) indicating there’s an edge between vertices a i and b i. It’s guaranteed that the input graph is a tree.
The last line of the input contains a list of n space-separated integers v 1, v 2, …, v n (|v i| ≤ 109).
Output
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.
Examples
Input
3
1 2
1 3
1 -1 1
Output
3
題意:
樹上每次可以將一個連通塊加一或者減一,但是要包含點。
求使得所有點爲0的最小操作次數。
思路:
將1作爲總的根節點,定義代表以爲根需要增加/修改的次數。
則有
然後
再消除的影響即可
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
typedef long long ll;
const int maxn = 2e5 + 7;
int head[maxn],nex[maxn],to[maxn],tot;
int a[maxn];
ll dp[maxn][2]; //0爲減少,1爲增加
void add(int x,int y) {
to[++tot] = y;
nex[tot] = head[x];
head[x] = tot;
}
void dfs(int u,int fa) {
for(int i = head[u];i;i = nex[i]) {
int v = to[i];
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]);
}
a[u] += dp[u][0] - dp[u][1];
if(a[u] > 0) {
dp[u][1] += a[u];
} else {
dp[u][0] += -a[u];
}
}
int main() {
int n;scanf("%d",&n);
for(int i = 1;i < n;i++) {
int x,y;scanf("%d%d",&x,&y);
add(x,y);add(y,x);
}
for(int i = 1;i <= n;i++) {
scanf("%d",&a[i]);
}
dfs(1,-1);
printf("%lld\n",dp[1][0] + dp[1][1]);
return 0;
}