#K44912. Task Order
Task Order
Task Order
You are given n tasks numbered from 1 to n and m dependency pairs. Each dependency pair (u, v) indicates that task u depends on task v, i.e. task v must be completed before task u.
Your job is to determine a valid order to complete all tasks. If there exists a valid ordering, output the sequence of tasks separated by a space. If there is no valid order because of a cyclic dependency among the tasks, output Impossible
.
Note: When multiple tasks are available to be performed, you should always choose the task with the smallest number. Formally, if you have a set \(S\) of available tasks, choose \(\min S\). This ensures a unique and deterministic ordering. The dependencies can be formulated as the following directed edges:
\( v \longrightarrow u \) for each dependency \( (u, v) \), meaning task \(v\) precedes task \(u\).
inputFormat
The input is read from standard input (stdin) and has the following format:
n m u1 v1 u2 v2 ... um vm
Here, n
is the number of tasks, and m
is the number of dependency pairs. Each of the next m
lines contains two integers \(u\) and \(v\), meaning that task \(u\) depends on task \(v\) (i.e. v must be completed before u).
outputFormat
Print the valid ordering of tasks as a sequence of integers separated by spaces. If no valid ordering exists (due to a cyclic dependency), print Impossible
.
5 4
1 2
2 3
4 3
4 5
3 2 1 5 4