#P4957. Alchemical Reactions

    ID: 18197 Type: Default 1000ms 256MiB

Alchemical Reactions

Alchemical Reactions

In ancient times, alchemists were known to work with a total of \(N\) distinct substances, numbered from 1 to \(N\). They discovered a series of interesting regularities called alchemical reactions. In one reaction, it is possible to transform a set of substances \(\{X_1, X_2, \dots, X_L\}\) into another set \(\{Y_1, Y_2, \dots, Y_R\}\). For example, the substance set \(\{1, 4, 5\}\) might react to produce the set \(\{2, 6\}\>.

Joško is a modern alchemist and he has an unlimited supply of \(M\) distinct substances denoted by \(A_1, A_2, \dots, A_M\). He is curious to know which substances can be created from his initial stock using the list of ancient alchemical reactions.

You are given a list of reactions. Each reaction can be applied any number of times, in any order, as long as the set of reactants required by that reaction is available. Determine all substances that Joško can produce.

inputFormat

The input consists of multiple lines:

  1. The first line contains two integers \(N\) and \(M\) where \(N\) is the total number of substances and \(M\) is the number of substances initially available.
  2. The second line contains \(M\) distinct integers \(A_1, A_2, \dots, A_M\) representing the substances Joško initially has.
  3. The third line contains a single integer \(R\), the number of reactions.
  4. Then \(R\) lines follow, each describing a reaction. Each reaction is given in the following format:
    L X_1 X_2 ... X_L T Y_1 Y_2 ... Y_T
    Here, \(L\) is the number of reactants, followed by \(L\) integers representing the reactant substances. Then \(T\) is the number of products, followed by \(T\) integers representing the product substances.

outputFormat

Output all the substances that can be produced (including the initial ones) in increasing order, separated by a single space.

sample

6 2
1 4
3
3 1 4 5 2 6
2 2 6 1 3
1 3 1 2
1 2 3 4 6

</p>