Connectedness

시간 제한1초메모리 제한1024 MB

요약
주어진 무방향 간선을 하나씩 추가해 나가며 그래프가 처음 연결되는 순간까지 추가한 간선 수를 구한다.
난이도

보통10점 중 5점

유형
그래프, 유니온 파인드, DFS
정답자
아직 제출이 없습니다

문제

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

If you are drawing in the edges one by one, how many edges did you add when the graph becomes connected for the first time.

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

Here are some useful definitions:

  • A graph is connected if between 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 allows travel from vertex vv to vertex uu as well.

입력

The input line of input 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 in the graph.

Each of the remaining MM lines contains two space-separated integers u_iu\_i and v_iv\_i (1≤u_i,v_i≤N)(1 \leq u\_i, v\_i \leq N), denoting an undirected edge from node u_iu\_i to node v_iv\_i. No edge connects a node to itself, and there is at most one edge between any pair of nodes.

출력

Print either the number of edges that you added the first time graph becomes connected and -1 otherwise.

예제3

  1. 예제 1

    입력
    2 0
    
    예상 출력
    -1
    
  2. 예제 2

    입력
    1 0
    
    예상 출력
    0
    
  3. 예제 3

    입력
    7 11
    1 4
    1 5
    1 6
    1 7
    2 3
    3 4
    3 5
    3 6
    4 7
    5 6
    6 7
    
    예상 출력
    6