#K8426. Task Ordering with Dependencies

    ID: 36380 Type: Default 1000ms 256MiB

Task Ordering with Dependencies

Task Ordering with Dependencies

You are given a set of tasks numbered from 1 to \(n\). Each task may depend on some other tasks. A task \(i\) can only be performed after all of its dependencies have been completed. Your task is to determine a valid order to complete all tasks. If such an order does not exist due to cyclic dependencies, output IMPOSSIBLE.

Input Format: The first line contains an integer \(n\) representing the number of tasks. The following \(n\) lines each describe a task. The \(i\)-th line starts with an integer \(k_i\), indicating the number of dependencies for task \(i\), followed by \(k_i\) space‐separated integers denoting the identifiers of tasks that must be completed before task \(i\). Tasks are numbered from 1 to \(n\).

Output Format: If a valid ordering exists, output a single line with the tasks in one valid order, separated by spaces. If no order exists, output IMPOSSIBLE.

Example:

Input:
4
1 2
0
1 2
1 3

Output:
2 1 3 4

inputFormat

The input is read from standard input (stdin) and has the following format:

  • The first line contains a single integer \(n\) (1 \(\leq\) \(n\) \(\leq\) 105) representing the number of tasks.
  • The next \(n\) lines each describe a task in order from task 1 to task \(n\). Each line begins with an integer \(k_i\) (the number of dependencies for the \(i\)-th task), followed by \(k_i\) integers specifying the tasks that must be completed before task \(i\).

outputFormat

If a valid ordering exists, output the tasks in one possible valid order (space-separated) on a single line. If no valid ordering exists, output IMPOSSIBLE.

## sample
4
1 2
0
1 2
1 3
2 1 3 4