#P6223. Farmer Money Redistribution
Farmer Money Redistribution
Farmer Money Redistribution
There are \( n \) farmers living in \( n \) different villages. These villages form a tree structure. Initially, each farmer has \( x \) units of money. For each farmer \( i \), a target value \( v_i \) is given. In each operation, a farmer may choose any amount of money from his own funds and transfer it to a farmer living in an adjacent village (i.e. there is an edge between their villages).
The task is to determine the minimum number of operations required so that every farmer ends up having at least \( v_i \) money.
Important Notes:
- The tree structure is given by \( n-1 \) edges connecting the villages.
- You can transfer an arbitrarily large amount in a single operation along an edge.
- An operation is defined as a transfer of money along one edge from one farmer to an adjacent one.
- If no transfer is needed along an edge (i.e. the net required transfer in that subtree is zero), then no operation is performed on that edge.
- The minimum number of operations is essentially the count of tree edges across which a nonzero amount of money needs to be transferred. </p>
Hint: Let \( r_i = x - v_i \) be the initial surplus (or deficit if negative) of farmer \( i \). Then, by performing a DFS on the tree (rooted arbitrarily) and computing the cumulative surplus of each subtree, you can decide for each edge whether a transfer is needed. If the cumulative surplus of a subtree is nonzero, then one transfer (operation) is needed on the edge connecting that subtree with its parent.
inputFormat
The first line contains two integers \( n \) and \( x \) where \( n \) is the number of farmers (and villages) and \( x \) is the initial amount of money each farmer has.
The second line contains \( n \) integers \( v_1, v_2, \ldots, v_n \), where \( v_i \) is the target money for the \( i^{th} \) farmer.
Each of the next \( n-1 \) lines contains two integers \( u \) and \( w \), representing an edge between village \( u \) and village \( w \) (indicating that the corresponding farmers are neighbors).
outputFormat
Output a single integer: the minimum number of operations required so that every farmer ends up with at least \( v_i \) money.
sample
3 10
10 5 15
1 2
1 3
2