
Sponsored
Sponsored
Use these hints if you're stuck. Try solving on your own first.
The problem can be solved using tree DP.
Using node <code>0</code> as the root, let <code>dp[x]</code> be the minimum number of edge reversals so node <code>x</code> can reach every node in its subtree.
Using a DFS traversing the edges bidirectionally, we can compute <code>dp</code>.<br /> <code>dp[x] = dp[y] +</code> (<code>1</code> if the edge between <code>x</code> and <code>y</code> is going from <code>y</code> to <code>x</code>; <code>0</code> otherwise), where <code>x</code> is the parent of <code>y</code>.
Let <code>answer[x]</code> be the minimum number of edge reversals so it is possible to reach any other node starting from node <code>x</code>.
Using another DFS starting from node <code>0</code> and traversing the edges bidirectionally, we can compute <code>answer</code>.<br /> <code>answer[0] = dp[0]</code><br /> <code>answer[y] = answer[x] +</code> (<code>1</code> if the edge between <code>x</code> and <code>y</code> is going from <code>x</code> to <code>y</code>; <code>-1</code> otherwise), where <code>x</code> is the parent of <code>y</code>.