#K12481. Cycle Detection in Communication Networks

    ID: 23700 Type: Default 1000ms 256MiB

Cycle Detection in Communication Networks

Cycle Detection in Communication Networks

You are given a directed graph representing a communication network among machines. Each node stands for a machine, and a directed edge from machine X to machine Y indicates a one-way communication from X to Y. Your task is to determine whether there exists a cycle within the network for each test case.

Formally, for a directed graph G=(V,E) where V is the set of nodes and E is the set of directed edges, you need to decide if there is a sequence of nodes \(v_1, v_2, \ldots, v_k\) with \(k \ge 1\) such that there is an edge from \(v_i\) to \(v_{i+1}\) for \(1 \le i < k\) and an edge from \(v_k\) back to \(v_1\).

For example, in a network with 4 machines and edges (1,2), (2,3), (3,4), and (4,1), a cycle exists. On the other hand, if the network has no cycles, output "No".

You are required to read the input from the standard input and output your results to the standard output.

inputFormat

The first line contains an integer \(T\) representing the number of test cases. Each test case is described as follows:

  • The first line of each test case contains two integers \(N\) and \(M\), where \(N\) is the number of machines (nodes) and \(M\) is the number of communications (directed edges).
  • This is followed by \(M\) lines. Each line contains two integers \(X\) and \(Y\) indicating a directed edge from machine \(X\) to machine \(Y\).

All machines are numbered from 1 to \(N\).

outputFormat

For each test case, output a single line containing "Yes" if there is a cycle in the communication network, or "No" if there is no cycle.

## sample
2
4 4
1 2
2 3
3 4
4 1
3 2
1 2
2 3
Yes

No

</p>