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.
3
1 2
1 3
1 -1 1
3
题意:
给出一棵树,编号为1~n,点有权值(有小于0的)
你可以做以下操作:
选择树的一棵子树,但是这棵子树必须包含节点1,你可以把这棵子树的所有节点的权值都加1或者都减1
问:至少需要多少个操作,才可以把所有点权都变为0
明显,必须先让深度大的节点点权变为0,最后让根节点点权变为0
一次dfs就可以了
1 #include<cstdio> 2 #include<cstring> 3 4 using namespace std; 5 6 #define ll long long 7 const int maxn=1e5+5; 8 inline ll max(ll a,ll b) 9 { 10 return a>b?a:b; 11 } 12 13 ll add[maxn]; //以i为根的子树需要做加法的次数 14 ll sub[maxn]; //以i为根的子树需要做减法的次数 15 //节点i为根的子树,做add[i]次加法和sub[i]次减法后,子树所有节点的点权都为0 16 ll w[maxn]; 17 struct Edge 18 { 19 int to,next; 20 }; 21 Edge edge[maxn<<1]; 22 int head[maxn]; 23 int tot=0; 24 25 void addedge(int u,int v) 26 { 27 edge[tot].to=v; 28 edge[tot].next=head[u]; 29 head[u]=tot++; 30 } 31 32 void dfs(int ,int ); 33 34 int main() 35 { 36 memset(head,-1,sizeof head); 37 int n; 38 scanf("%d",&n); 39 for(int i=1;i<n;i++) 40 { 41 int u,v; 42 scanf("%d %d",&u,&v); 43 addedge(u,v); 44 addedge(v,u); 45 } 46 for(int i=1;i<=n;i++) 47 { 48 scanf("%I64d",&w[i]); 49 } 50 dfs(1,-1); 51 printf("%I64d ",add[1]+sub[1]); 52 return 0; 53 } 54 55 void dfs(int u,int pre) 56 { 57 add[u]=0; 58 sub[u]=0; 59 for(int i=head[u];~i;i=edge[i].next) 60 { 61 int v=edge[i].to; 62 if(v==pre) 63 continue; 64 dfs(v,u); 65 add[u]=max(add[u],add[v]); 66 sub[u]=max(sub[u],sub[v]); 67 } 68 w[u]=w[u]+add[u]-sub[u]; 69 if(w[u]>=0) 70 sub[u]+=w[u]; 71 else 72 add[u]+=(-w[u]); 73 }