Problem 427
Operations to Connect a Network
Medium · 20 pts · Graph, Union Find, Depth-First Search
Problem
There are N computers (labelled 1 to N) and M cables, each connecting two computers. In one operation you can unplug a cable from between two computers and use it to connect any other pair. Find the minimum number of operations needed so that every computer can reach every other one, or -1 if there are not enough cables. You need at least N - 1 cables in total; if you have them, the answer is the number of connected components minus one.
Input
First line: N and M. Next M lines: a cable u v.
Output
Print the minimum number of operations, or -1.
Constraints
1 <= N <= 100000; 0 <= M <= 100000; no repeated cables
Example input
4 3 1 2 1 3 2 3
Example output
1
Explanation
With 4 computers and cables 1-2, 1-3, 2-3, computer 4 is cut off. The cable 2-3 is redundant (1, 2 and 3 are connected without it), so moving it to join computer 4 takes one operation.