#K71697. Task Execution Order
Task Execution Order
Task Execution Order
You are given a set of tasks labeled from 1 to t and a list of dependency relations. Each dependency is represented as a pair of integers (a, b), meaning that task a depends on task b – i.e. task b must be executed before task a.
Your task is to determine a valid execution order of all tasks such that all dependency constraints are satisfied. If there exists any cycle in the dependencies (i.e. it is impossible to complete all tasks without violating a prerequisite), then output -1.
The dependency condition can be expressed in LaTeX as follows: For every dependency \( (a, b) \), task \( b \) must precede task \( a \). In other words, if we denote the execution order as a sequence \( [x_1, x_2, \dots, x_t] \), then for every \( (a, b) \) there exists indices \( i, j \) such that \( x_i = b,\, x_j = a \) and \( i < j \).
inputFormat
The input is read from stdin and has the following format:
t m a1 b1 a2 b2 ... am bm
Where:
t
is an integer representing the number of tasks (tasks are numbered from 1 to t).m
is the number of dependency relations.- Each of the next
m
lines contains two integersa
andb
indicating that taska
depends on taskb
(i.e. taskb
must be executed before taska
).
outputFormat
If a valid task execution order exists, output the tasks in that order as a space‐separated list on one line. If there is no valid order due to cyclic dependencies, output -1
.
Output is to be written to stdout.
## sample4
4
2 1
3 1
4 2
4 3
1 2 3 4