#C4374. Unique Book Ordering Problem

    ID: 47905 Type: Default 1000ms 256MiB

Unique Book Ordering Problem

Unique Book Ordering Problem

You are given several categories of books. Each category contains a sequence of ISBN numbers. Additionally, there are ordering constraints between the categories. Each constraint is given as a pair of integers (a) and (b), meaning that all books in category (a) must come before any book in category (b) in the final order.

Your task is to determine the unique ordering of all books by concatenating the books in the categories in an order that satisfies all the constraints. The order in which books appear within each category is fixed (as given in the input). When multiple categories are available to choose (i.e. they have no pending constraints), you should always choose the one with the smallest index. If it is not possible to determine an ordering that satisfies all constraints (for example, due to a cycle in the dependency graph), output "Impossible".

Note: The ordering is considered unique if, by following the rule of always picking the smallest available category index, you obtain exactly one valid ordering. This rule also applies for cases with no constraints, where the categories should be ordered according to their input order.

inputFormat

The input is read from standard input (stdin). The first line contains an integer (T) representing the number of test cases. For each test case:

  • The first line contains two integers (n) and (m): the number of categories and the number of constraints.
  • The next (n) lines each contain a sequence of ISBN numbers (integers) separated by spaces, representing the books in that category (the order is fixed).
  • The following (m) lines each contain two integers (a) and (b), indicating that the books in category (a) must come before the books in category (b).

outputFormat

For each test case, output a single line. If a valid ordering according to the rules exists, print the ISBN numbers in that order separated by a single space. Otherwise, print "Impossible".## sample

1
3 2
1001 1002 1003
2001 2002
3001 3002 3003
1 2
2 3
1001 1002 1003 2001 2002 3001 3002 3003