#C1895. Ecosystem Simulation
Ecosystem Simulation
Ecosystem Simulation
An ecosystem can be modeled as a directed graph where each species may prey upon another. In this problem, you are given n species and m predator-prey relationships. Your task is to first detect if the ecosystem contains any cycles using Kahn's Algorithm (topological sort). A cycle indicates that the ecosystem is unstable. If no cycle is detected, output the top-level species, that is, species that are not preyed upon by any other species, in sorted order.
The relationships are represented by directed edges. When a cycle exists, simply output Cycle
. Otherwise, output the list of top-level species separated by a single space.
inputFormat
The input is read from stdin
and has the following format:
- The first line contains two space-separated integers n and m, representing the number of species and the number of predator-prey relationships, respectively.
- The next m lines each contain two space-separated integers a and b, indicating a directed edge from species a to species b (i.e. species a preys on species b).
outputFormat
Write your answer to stdout
as follows:
- If a cycle is detected in the ecosystem, output the string
Cycle
. - If no cycle is present, output the top-level species (those with no incoming edges) in ascending order, separated by a single space.
4 4
1 2
2 3
3 1
3 4
Cycle