Sponsored
Sponsored
Use these hints if you're stuck. Try solving on your own first.
Suppose that we connected node <code>a</code> in tree1 with node <code>b</code> in tree2. The diameter length of the resulting tree will be the largest of the following 3 values: <ol> <li>The diameter of tree 1.</li> <li>The diameter of tree 2.</li> <li>The length of the longest path that starts at node <code>a</code> and that is completely within Tree 1 + The length of the longest path that starts at node <code>b</code> and that is completely within Tree 2 + 1.</li> </ol> The added one in the third value is due to the additional edge that we have added between trees 1 and 2.
Values 1 and 2 are constant regardless of our choice of <code>a</code> and <code>b</code>. Therefore, we need to pick <code>a</code> and <code>b</code> in such a way that minimizes value 3.
If we pick <code>a</code> and <code>b</code> optimally, they will be in the diameters of Tree 1 and Tree 2, respectively. Exactly which nodes of the diameter should we pick?
<code>a</code> is the center of the diameter of tree 1, and <code>b</code> is the center of the diameter of tree 2.