I am a beginner learning algorithms and currently working on a problem about finding the total sum of shortest distances in an unweighted tree. Here’s the specific scenario:
The tree has nodes that belong to three different colors: red, yellow, and blue. The number of nodes for each color is the same. I want to pair each red node with a blue node and find the total sum of their shortest distances.
I have checked previous post but only seen questions regrading calculating distance between two specific nodes. So far, I am using BFS to traverse each node, but I’m stuck on how to record the unpaired blue and red nodes and compute the total shortest distances efficiently. Should I be using dynamic programming for this? I am not sure if my strategy is correct or not.
I would really appreciate any hints or guidance. Thank you so much in advance!
jack94243 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
3
Root the tree arbitrarily and perform a depth-first search. At each node, find the number of red and blue nodes in its subtree that have not yet been paired (this can be computed directly from the results of its children).
Next, pair as many nodes as possible (i.e. the number of pairs here is the minimum of the number of red nodes and the number of blue nodes). Add the number of remaining unpaired nodes to the total distance sum as these nodes need to traverse the edge to the parent on its path to the matching node.
This solution is O(V + E)
or just O(V)
since E = V - 1
in a tree.
2