Alchemy
Time limit1sMemory limit64 MB
Given starting substances and reactions that each require holding a whole set of substances to produce another set, find everything Josko can eventually obtain.
- Level
Medium7 of 10
- Topics
- Graph, BFS, Hash map, Implementation
- Solved
- No attempts yet
Problem
Back when alchemists were still searching for gold, the world knew different substances, numbered through . Years of work gave the alchemists a list of alchemical reactions. One reaction turns the substance set into another substance set . For example, the set reacts once and produces the new set .
Josko is a modern alchemist and holds different substances . 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.
Input
The first line contains the integers and ().
The second line contains integers (), the labels of the substances Josko has at the start.
The third line contains the integer (), the number of known reactions.
The following lines contain the list of reactions. Each reaction is described with three lines.
- The first line contains the integers and ().
- The second line contains distinct integers ().
- The third line contains distinct integers ().
This reaction turns the substance set into the substance set .
The sum of all values of does not exceed . The sum of all values of does not exceed .
Output
The first line must contain the integer , the number of obtainable substances.
The second line must contain the labels of those substances, sorted in ascending order and separated by single spaces. The substances Josko starts with count as obtainable.
Notes
The first example has two reactions. The first one turns the set into , and the second one turns into . Josko starts with , so the first reaction gives him substance and leaves him with . The second reaction then gives him substance as well.
In the second example Josko starts with . The second reaction gives him substance , and the third reaction then gives him substance . The first reaction can never be used because he never has substance .