Tree
InterviewTime limit2sMemory limit512 MB
Given up to 10 graphs, decide for each whether it is a tree, allowing self-loops and duplicate edges.
- Level
Medium4 of 10
- Topics
- Graph, Union-find, DFS
- Solved
- No attempts yet
Problem
A tree is a graph with the following three properties.
- It is connected. Starting from any node you can reach every other node along edges.
- Removing one edge breaks the connection. Some node can no longer be reached.
- Adding one edge between two existing nodes A and B creates a cycle. A cycle exists when there is more than one way to get from A to B.
Given a graph, decide whether it is a tree.
Input
The first line contains an integer , the number of graphs to check. is at most 10.
Each graph is given in the following format.
The first line contains the number of nodes , where . The nodes are numbered from 1 to .
The next line contains the number of edges , where .
The next lines each contain two integers and , the two nodes that one edge connects. and can be equal, and the same pair can appear more than once.
The sum of over all graphs is at most .
Output
For each graph, print one line: tree if the graph is a tree, and graph otherwise.