Here is the algorithm:
Run Union-Find to identify components
Find one representative per component
Output where is the number of components
Output edges connecting representatives in a chain The tricky part is extracting representatives from Union-Find. Loop through all nodes and collect unique component IDs. Then pick one node per ID and chain them together. Simple once you see it.