Editorial
Suppose first that is a star. Every vertex except its center is a leaf of . Removing a leaf from a tree leaves the remaining vertices connected, so if a good existed, no leaf of could also be a leaf of . Every tree has at least two leaves, while only the center of the star is not a leaf of . This is impossible.
Now suppose that is not a star. Then there is an edge whose two endpoints both have degree at least . Choose a neighbor of other than , and a neighbor of other than . The four vertices are distinct and form the path
in .
On these four vertices, let be the path
The two trees have no common edge, and their leaf sets are disjoint, so there is no common connected subset of size or .
Treat the four vertices as a connected root set and add every other vertex in increasing distance from this set. Let be a new vertex, and let be its parent in among the vertices already added. The current is always a path. Choose an edge of this path that is not incident to , delete , and add and . Thus we subdivide one edge of the path by .
The current path always has at least three edges. At most two path edges are incident to one vertex , so such an edge always exists.
It remains to prove that this operation preserves the good relationship. Let be the old vertex set, and suppose that after adding there is a proper subset connected in both trees.
If , restoring the deleted edge cannot destroy connectivity in . Hence would already have been connected in both old trees. The only possible exception is , but after removing from the new , the path is broken at the deleted edge , so is not connected there.
If , let . Since is a leaf of , we have , and is connected in the old . In , suppressing and restoring makes connected in the old tree as well. By the old good relationship, is either one vertex or all of . If , then is the whole new vertex set and is not forbidden. If , then , but was chosen not to be incident to , so is not connected in the new . This is a contradiction.
Therefore a solution exists exactly when is not a star. Using a linked list for the path , the construction runs in time. Over all test cases, the time complexity is and the memory usage is .
Solution written by GPT5.6