#K10351. Cycle Detection in a Road Network
Cycle Detection in a Road Network
Cycle Detection in a Road Network
You are given an undirected graph representing a road network of villages. The graph contains n villages and m bidirectional roads connecting pairs of villages. A cycle in this context is defined as a sequence of roads:
\( (v_1, v_2), (v_2, v_3), \ldots, (v_{k-1}, v_k), (v_k, v_1) \)
where all \(v_i\) (\(1 \leq i \leq k\)) are distinct and \(k \ge 3\). Your task is to determine whether the road network contains at least one cycle.
If there is a cycle, print YES
; otherwise, print NO
.
inputFormat
The input is read from stdin
and has the following format:
- The first line contains two integers \(n\) and \(m\) representing the number of villages (nodes) and the number of roads (edges), respectively.
- The next \(m\) lines each contain two integers \(u\) and \(v\) representing a bidirectional road between villages \(u\) and \(v\).
outputFormat
Print a single line to stdout
containing YES
if there exists a cycle in the network, or NO
otherwise.
5 5
1 2
1 3
2 3
3 4
4 5
YES
</p>