You must schedule n tasks numbered 1 through n. Some tasks have prerequisites: an edge u v means task u must be completed strictly before task v. You want a single ordering of all n tasks that respects every prerequisite.
Many orderings can be valid, so output the lexicographically smallest one: among all valid orderings, choose the sequence that is smallest when compared position by position (i.e., prefer a smaller task number as early as possible). Concretely, at every step, schedule the smallest-numbered task whose prerequisites have all already been scheduled.
If the prerequisites are contradictory (they contain a cycle) so that no valid ordering exists, print the single token CYCLE instead.
Line 1: two integers n and m \u2014 the number of tasks and the number of prerequisite edges.
Next m lines: two integers u v (1-indexed) meaning task u must come before task v.
If a valid ordering exists: the n task numbers in lexicographically smallest valid order, separated by single spaces, on one line.
Otherwise: the single token CYCLE.
u and v of an edge may satisfy u == v (a self-edge, which forms a cycle).Ordering must reorder numbers
Input
3 2 3 1 1 2
Expected
3 1 2
Explanation
Task 3 must precede 1, and 1 must precede 2. The only valid order is 3 1 2, which is therefore also the lexicographically smallest.
Contradictory prerequisites
Input
3 3 1 2 2 3 3 1
Expected
CYCLE
Explanation
The edges form the cycle 1\u21922\u21923\u21921, so no task can start; the answer is CYCLE.
Ready to solve this?
Sign in to open the editor, run your code against the sample tests, and submit against the full test suite.
Sign in to solve →