A data center has n servers, numbered 1 through n, joined by m network cables. Each cable directly connects two distinct servers. In one operation you may unplug any one existing cable and plug it back in between any two servers you like. Determine the minimum number of operations needed to make the whole rack connected (every server reachable from every other), or report -1 if it is impossible.
n and m.m lines: two integers u and v (1-indexed, u != v), a cable between servers u and v. The same pair may appear more than once.A single integer: the minimum number of operations, or -1 if the rack cannot be fully connected.
Example 1
Input
6 5 1 2 3 4 1 2 3 4 1 3
Expected
2
Explanation
Servers group as {1,2,3,4}, {5}, {6}: 3 components. There are 5 cables (2 of them spare duplicates), enough to bridge the 3 groups with 2 moves.
Example 2
Input
4 2 1 2 3 4
Expected
-1
Explanation
There are 4 servers but only 2 cables; at least 3 cables are needed to connect 4 servers, so it is impossible: -1.
Ready to solve this?
Sign in to open the editor, run your code against the sample tests, and submit against the full test suite.
Sign in to solve →