Given starting substances and reactions that each require holding a whole set of substances to produce another set, find everything Josko can eventually obtain.
Medium7GraphBFSHash mapImplementationNo attempts yetTime limit1sMemory limit64 MBBack when alchemists were still searching for gold, the world knew N different substances, numbered 1 through N. Years of work gave the alchemists a list of alchemical reactions. One reaction turns the substance set {X1,X2,…,XL} into another substance set {Y1,Y2,…,YR}. For example, the set {1,4,5} reacts once and produces the new set {2,6}.
Josko is a modern alchemist and holds M different substances A1,A2,…,AM. He has an unlimited amount of each of them. He can run a reaction only while he holds every substance on its left side, and running it gives him every substance on its right side. A reaction consumes nothing, and a substance he has produced can be used in later reactions.
Find every substance Josko can obtain from the list of ancient reactions.
The first line contains the integers N and M (1≤M≤N≤100000).
The second line contains M integers Ai (1≤Ai≤N), the labels of the substances Josko has at the start.
The third line contains the integer K (1≤K≤100000), the number of known reactions.
The following 3K lines contain the list of reactions. Each reaction is described with three lines.
This reaction turns the substance set {X1,X2,…,XL} into the substance set {Y1,Y2,…,YR}.
The sum of all values of L does not exceed 100000. The sum of all values of R does not exceed 100000.
The first line must contain the integer X, the number of obtainable substances.
The second line must contain the X labels Bi of those substances, sorted in ascending order and separated by single spaces. The substances Josko starts with count as obtainable.
The first example has two reactions. The first one turns the set {1,2} into {3}, and the second one turns {1,3} into {4}. Josko starts with {1,2}, so the first reaction gives him substance 3 and leaves him with {1,2,3}. The second reaction then gives him substance 4 as well.
In the second example Josko starts with {1,4,5}. The second reaction gives him substance 6, and the third reaction then gives him substance 2. The first reaction can never be used because he never has substance 3.