Under construction

Still being built. Things may change

Connectedness

Interview

Time limit1sMemory limit1024 MB

Summary
Given N vertices and M edges added in order, find how many edges are drawn when the graph first becomes connected, or -1 if it never does.
Level

Easy3 of 10

Topics
Union-find, Graph
Solved
No attempts yet

Problem

You are given an undirected graph G=(V,E)G=(V,E).

Draw the edges one by one, in the order they are given. Find how many edges you have drawn when the graph first becomes connected.

If the graph never becomes connected after all edges are drawn, output -1.

A graph is connected if, for any two vertices u,v∈Vu,v \in V, you can reach uu from vv along a path of edges.

A graph is undirected if every edge from a vertex uu to a vertex vv also lets you travel from vv to uu.

Input

The first line contains two space-separated integers NN (1≤N≤106)(1 \leq N \leq 10^6) and MM (0≤M≤min⁡(106,(N2)))(0 \leq M \leq \min(10^6, \binom{N}{2})), the number of vertices and edges.

Each of the next MM lines contains two space-separated integers uiu_i and viv_i (1≤ui,vi≤N)(1 \leq u_i, v_i \leq N), an undirected edge between uiu_i and viv_i. No edge connects a vertex to itself, and there is at most one edge between any pair of vertices.

Output

Print the number of edges drawn the first time the graph becomes connected, or -1 if it never does.

Examples3

  1. Example 1

    Input
    2 0
    
    Expected output
    -1
    
  2. Example 2

    Input
    1 0
    
    Expected output
    0
    
  3. Example 3

    Input
    7 11
    1 4
    1 5
    1 6
    1 7
    2 3
    3 4
    3 5
    3 6
    4 7
    5 6
    6 7
    
    Expected output
    6