Cactus Meets Torus
Time limit3sMemory limit1024 MB
Given a cactus as edge-disjoint paths, decide if it can be drawn on a torus so that cutting along any one cycle keeps the sheet in one piece.
Problem
Alice has a nice cactus graph that she wants to place on a sheet of paper. Eve threatens to take one cycle of this cactus and cut the paper along all edges on this cycle. The sheet of paper would then be divided into two parts, and Alice would be upset. Luckily, Barbara just gave Alice a paper torus: a sheet of paper whose top and bottom edges are connected, and whose left and right edges are connected, without twisting. On a torus, you can sometimes cut paper along all edges of a cycle and it still remains in one piece. Help Alice determine whether she can place her cactus on a torus so that Eve cannot cut paper along one cycle to divide the torus into two unconnected pieces.
A cactus is a connected undirected graph in which every edge lies on at most one simple cycle. Intuitively, a cactus is a generalization of a tree where some cycles are allowed. Multiedges (multiple edges between a pair of vertices) and loops (edges that connect a vertex to itself) are not allowed in a cactus.
A graph is placed on a sheet of paper if each vertex is a point on the sheet, each edge is a segment between the points of its vertices, and these segments intersect only at their ends. On a torus, segments may go through the sheet edges any number of times.
Input
The input consists of one or more independent test cases.
The first line of each test case contains two integers and (; ), where is the number of vertices in the graph. Vertices are numbered from to . The edges of the graph are given as a set of edge-distinct paths, where is the number of such paths.
Each of the following lines contains a path in the graph. A path starts with an integer () followed by integers from to . These integers are the vertices of the path. Adjacent vertices in a path are distinct. A path may pass through the same vertex several times, but every edge is traversed exactly once in the whole test case. The graph has no multiedges, so there is at most one edge between any pair of vertices.
The last line of the input contains two zeros. It is not a test case and marks the end of the input, so it requires no output.
All graphs in the input are cacti. The sum of all values of and the sum of all values of over the whole input each do not exceed .
Output
For each test case, print a single line with "Yes" if the cactus can be placed on a torus, or "No" otherwise.
Hint
One way to place the cactus from the first case on a torus is shown in the picture.
