Approach hintTry it first, then revealHide
Compute the cost for one root together with subtree sums of a. Moving the root from u to its child v changes the cost by total - 2 * sub[v], so one more DFS evaluates every root in O(n).
Compute the cost for one root together with subtree sums of a. Moving the root from u to its child v changes the cost by total - 2 * sub[v], so one more DFS evaluates every root in O(n).