Editorial
Let be the number of connected components of the graph.
Adding one edge between two different connected components merges those two components, so one added edge can decrease the number of components by at most . To make the whole graph connected, only one component must remain, so at least edges are necessary.
Conversely, choose one representative vertex from each connected component and connect these representatives in a chain. This uses exactly new edges and makes the graph connected. Therefore, the answer is .
The number of connected components can be found with a disjoint set union data structure. Initially, every vertex is in its own set. For each input edge , merge the sets containing the two endpoints. Finally, count the number of distinct representatives.
The time complexity is .
Solution written by GPT5.5