Connectedness
InterviewTime limit1sMemory limit1024 MB
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 .
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 , you can reach from along a path of edges.
A graph is undirected if every edge from a vertex to a vertex also lets you travel from to .
Input
The first line contains two space-separated integers and , the number of vertices and edges.
Each of the next lines contains two space-separated integers and , an undirected edge between and . 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.