codeforces275D - Zero Tree树形dp

这个题一开始做的时候有一念想到树形dp然后被自己那想歪的思路直接给带成了递归,当时没能考虑到把加减分开直接abs累加了惭愧惭愧

D. Zero Tree

time limit per test

2 seconds

memory limit per test

256 megabytes

input

standard input

output

standard output

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:

  1. Select the subtree of the given tree that includes the vertex with number 1.
  2. 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 ai and bi (1 ≤ ai, bi ≤ nai ≠ 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).

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 %I64dspecifier.

Examples

input

Copy

3
1 2
1 3
1 -1 1

output

Copy

3

dp数组0表示要加几个1才能到目前的数,1表示再减几个1才能到目前的数。每个节点最多有两个儿子(每个点的数值正数代表加负数代表减)然后再对当前节点操作求它"原来"的数值即把他加上的值减去减去的值加上,大于0就说明少加了小于零就少减了再给他补上最后回到1节点(必经点),我没有用邻接表直接vector塞了然后加个标记数组

#include 
#include 
#include 
#include 
#include 
#define MAXN 20
#define INF 0x3f3f3f3f
 
using namespace std;
bool cmp(int a,int b)
{
    return a>b;
}
vectora[100020];
long long e[200003],dp[200000][2],maxx[200001],minn[200001];
bool ha[2000020];
void dfs(int x)
{
    ha[x]=1;
    dp[x][0]=dp[x][1]=0;
    for(int i=0;i0)
        dp[x][0]+=e[x];
    else
        dp[x][1]-=e[x];
 
    return ;
}
int main()
{
    long long n,m;
    cin>>n;
    for(int i=1;i>x>>y;
        a[x].push_back(y);
        a[y].push_back(x);
    }
    for(int i=1;i<=n;i++)
    {
        cin>>e[i];
    }
    memset(ha,false,sizeof(ha));
    dfs(1);
    long long ans=dp[1][1]+dp[1][0];
    cout<

 

你可能感兴趣的:(dp)