#K60562. Task Ordering by Prerequisites
Task Ordering by Prerequisites
Task Ordering by Prerequisites
You are given N tasks (numbered from 1 to N) and M prerequisites. Each prerequisite is given as a pair \( (a, b) \) indicating that task a must be completed before task b. Your goal is to determine a valid order in which all tasks can be completed while satisfying all the prerequisites. If there is no such ordering (i.e. if the dependency graph contains a cycle), print "Impossible".
The problem can be modeled using a directed graph. Let the tasks be represented by nodes, and prerequisites by directed edges. A valid order corresponds to a topological sort of the graph. In mathematical terms, if we let \( G = (V, E) \) where \( V = \{1, 2, \dots, N\} \) and \( E \) is the set of prerequisite pairs, then you must find an ordering \( \sigma: V \to \{1, 2, \dots, N\} \) such that for every edge \( (a, b) \in E \), \( \sigma(a) < \sigma(b) \). If no such ordering exists, output "Impossible".
inputFormat
The first line contains two space-separated integers N and M, representing the number of tasks and the number of prerequisites respectively. The next M lines each contain two integers a and b, representing a prerequisite that task a must be completed before task b can be started.
Input is read from standard input (stdin).
outputFormat
If a valid topological order exists, print the order as space-separated integers in one line. If there is no valid order, print "Impossible". The result should be written to standard output (stdout).
## sample4 3
1 2
3 2
4 3
1 4 3 2