#C2991. Task Ordering with Dependencies and Priorities
Task Ordering with Dependencies and Priorities
Task Ordering with Dependencies and Priorities
You are given n tasks labeled from 1 to n and m dependencies. Each dependency is given as a pair (u, v) indicating that task u must be completed before task v. In addition, each task is assigned a priority. Your goal is to determine an order in which the tasks can be completed such that:
- The ordering is a valid topological order i.e. all dependencies are satisfied.
- If a valid topological order exists, the final ordering is obtained by sorting the tasks from the topological order in descending order of their priorities.
If there exists a cycle in the dependencies, output Not possible
. Otherwise, output the list of tasks separated by a space, following the above criteria.
Note: The priorities are given as integers and a higher number indicates a higher priority.
The final answer should be formatted as a space separated string, where task numbers are 1-indexed.
inputFormat
The input is read from stdin and has the following format:
n m p1 p2 ... pn u1 v1 u2 v2 ... um vm
- The first line contains two integers:
n
(the number of tasks) andm
(the number of dependencies). - The second line contains
n
integers representing the priorities of the tasks. - The next
m
lines each contain two integersu
andv
, indicating that tasku
must be completed before taskv
.
outputFormat
The output is written to stdout. It should be a single line containing either:
- A space separated list of task numbers in the determined order (1-indexed), or
- The string
Not possible
if no valid ordering exists due to cyclic dependencies.
4 2
3 2 5 4
1 2
3 4
3 4 1 2