Wooksin-ness of a graph
InterviewTime limit1sMemory limit1024 MB
Given undirected graphs, find the fewest edges to add so the graph contains a cycle, or print -1 if that is impossible.
- Level
Easy3 of 10
- Topics
- Graph, Union-find, Implementation
- Solved
- No attempts yet
Problem
Problem
At the headquarters of algospot.com, Toivoa "the chairman" kept pestering Astein "the slave" for a new graph problem for a long time. So Astein came up with the following problem.
The Wooksin-ness of an undirected graph is the minimum number of additional edges needed for the graph to contain a cycle. Formally:
Loops (edges that start and end at the same vertex) and multiple edges between the same pair of vertices are not allowed.
Write a program that calculates the Wooksin-ness of a given graph.
Input
Input
The input consists of test cases. The first line contains the number of test cases .
The first line of each test case contains two integers and (, ), where is the number of vertices and is the number of edges. The vertices are numbered from to . Each of the following lines contains two integers, the numbers of the two vertices joined by an edge.
The input contains no loops. There is at most one edge between any pair of vertices.
Output
Output
For each test case, print one line containing the minimum number of edges that must be added to the graph so that it contains a cycle. If this is impossible, print .