Caterpillar
Time limit1sMemory limit128 MB
Given up to 100 nodes, decide whether the graph is a connected tree whose every node lies on or adjacent to some single path.
- Level
Medium5 of 10
- Topics
- Graph, DFS, Tree, Implementation
- Solved
- No attempts yet
Problem
An undirected graph is called a caterpillar if it is connected, has no cycles, and contains a path such that every node is either on this path or adjacent to a node on the path. Such a path is called the spine of the caterpillar, and the spine need not be unique. Your task is to check graphs to determine whether they are caterpillars.
Input
There are multiple test cases. Each test case starts with a line containing , the number of nodes, numbered through (a value of indicates end-of-input). The next line contains an integer , the number of edges. The following lines contain pairs of node numbers, each pair n1 n2 indicating an undirected edge between nodes n1 and n2; this list may span multiple lines. You may assume that and . Do not assume that the graphs are connected or acyclic.
Output
For each test case, produce one line of output. For the -th graph (numbering from ), print
Graph g is a caterpillar.
if the graph is a caterpillar, or
Graph g is not a caterpillar.
otherwise.