#K84787. Graph Cycle Detection

    ID: 36497 Type: Default 1000ms 256MiB

Graph Cycle Detection

Graph Cycle Detection

Given an undirected graph with \(n\) vertices and \(m\) edges, determine whether there exists a simple cycle. A simple cycle is defined as a cycle that does not repeat any vertex or edge except for the starting vertex which is repeated at the end. If such a cycle exists, output YES on the first line, and on the second line, output the sequence of vertices forming the cycle (with the first vertex repeated at the end). If there are multiple cycles, any one of them may be printed. If no cycle exists, simply output NO.

Mathematically, a cycle is a sequence of distinct vertices \(v_1, v_2, \ldots, v_k\) such that there is an edge between \(v_i\) and \(v_{i+1}\) for \(1 \le i < k\), and there is an edge between \(v_k\) and \(v_1\), with \(k \ge 3\).

inputFormat

The input is given via standard input in the following format:

  • The first line contains two integers \(n\) and \(m\): the number of vertices and edges, respectively.
  • The next \(m\) lines each contain two integers \(u\) and \(v\) representing an undirected edge between vertices \(u\) and \(v\>.

outputFormat

If a simple cycle exists, print YES on the first line and then print the cycle as a sequence of vertices on the second line (the starting vertex must appear again at the end). If no simple cycle exists, print NO.

## sample
4 4
1 2
2 3
3 4
4 1
YES

1 2 3 4 1

</p>