Zero Tree CodeForces - 275D(树形dp)

    技术2024-10-28  22

    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作为总的根节点,定义 d p [ i ] [ 0 / 1 ] dp[i][0/1] dp[i][0/1]代表以 i i i为根需要增加/修改的次数。 则有 d p [ u ] [ 0 ] = m a x ( d p [ v ] [ 0 ] ) dp[u][0]=max(dp[v][0]) dp[u][0]=max(dp[v][0]) d p [ u ] [ 1 ] = m a x ( d p [ v ] [ 1 ] ) dp[u][1]=max(dp[v][1]) dp[u][1]=max(dp[v][1]) 然后 a [ u ] + = d p [ u ] [ 0 ] − d p [ u ] [ 1 ] a[u] +=dp[u][0]-dp[u][1] a[u]+=dp[u][0]dp[u][1] 再消除 a [ u ] a[u] a[u]的影响即可

    #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; }
    Processed: 0.012, SQL: 9