problems / 153

Rewiring the Lab

easy union-find graphs 1000 ms · 256 MB

Rewiring the Lab

A university computer lab has n computers, numbered from 1 to n, and m network cables. Each cable directly links two different computers. Over the years the cabling has become a mess: some pairs are linked by several cables, some cables close loops, and some computers have been cut off from the rest.

Two computers can talk to each other if one can be reached from the other by following cables, possibly passing through other computers. The lab technician wants every computer to be able to talk to every other one. No new cables can be bought, but in one move the technician can unplug any single cable from both of its ends and plug it back in between any two different computers.

Find the minimum number of moves needed, or report that it can't be done with the cables the lab has.

Input

The first line contains two integers n and m (1 ≤ n ≤ 10^5, 0 ≤ m ≤ 2·10^5): the number of computers and the number of cables.

Each of the next m lines contains two integers a_i and b_i (1 ≤ a_i, b_i ≤ n, a_i ≠ b_i): the computers joined by the i-th cable. Several cables may join the same pair of computers.

Output

Print one integer: the minimum number of moves after which every computer can reach every other one, or -1 if that's impossible no matter how the cables are rearranged.

Notes

In the first example, computers 1, 2 and 3 already reach each other, computers 4 and 5 form a second group, and computer 6 is on its own. The cables 3–1 and 2–1 are not needed to keep the first group together, so one of them can be re-plugged between 3 and 4 and the other between 5 and 6: two moves.

In the second example the lab has only 3 cables, but linking 5 computers together needs at least 4.

Example 1

Input

6 5
1 2
2 3
3 1
4 5
2 1

Output

2

Example 2

Input

5 3
1 2
3 4
4 5

Output

-1

Hints · reveal one at a time if you're stuck

Hint 1

Count the groups of computers that can already reach each other. How many cables must any final layout use at least, and how much can one moved cable change the number of groups?

Hint 2

A cable that closes a loop can be unplugged without splitting its group, so such cables are spare. Check whether there are enough spare cables to join all the groups, with the -1 case handled first. Union-find over the cables gives you the group count.

report an issue Prefer your own editor? sooks prep 153 (CLI)
Sign in to run code

Run your code on the examples, or submit it against every test.