I understood your question how to ask to find a pair of nodes from the set F, so that the only way between these two nodes is to the extent possible. The path is unique because your graph is a tree.
The problem can be solved trivially by running DFS from each node in F, as you mentioned, to solve O (nk), where n is the size of the graph and k is the size of the set F.
However, you can solve this problem faster with a separation and subjugation approach. Select any node R from the graph and use one DFS to tab the distances Dist (R, a) to all other node aa and at the same time split the nodes into subtrees S1, ..., Sm, where m is the number of edges from R; those. these are m trees hanging in the root of R. Now for any f and g belonging to different subtrees, it is satisfied that the path between them has edges Dist (R, f) + Dist (R, g), therefore, we can find the longest such path in O (k ^ 2) time. In addition, you must then relate to the subtasks S1, ..., Sm in order to cover the case when the longest path is inside one of these trees. The overall complexity may be lower than O (nk), but the math remains as an exercise for the reader.
source share