Alchemy
Алхімія
Statement
There are K kinds of substances and N kinds of alchemical reactions. Each reaction consumes a fixed set of input substances and produces a fixed set of output substances, taking a fixed amount of time to complete. Any substance obtained from a reaction can be extracted in pure form and used freely — there's always enough of any substance for any use, and a substance produced by one reaction can immediately feed another. Reactions may run simultaneously.
Write a program ALCHEMY that, given the substances and reactions, finds
the minimum time needed to obtain a target substance.
Input / Output
The first line of input file ALCHEMY.DAT contains four integers: K
(3 ≤ K ≤ 250) — the number of substances, N (3 ≤ N ≤ 500) — the number of
reactions, M (1 ≤ M < K) — the number of substances available at the start,
and the number of the target substance. N blocks follow, each describing
one reaction in three lines: the time the reaction takes, then the count
and list of input substances, then the count and list of output substances.
Substances available from the start are numbered 1..M; all others are
numbered M+1..K. The sum of all reaction times does not exceed 2·10⁹.
The single line of output file ALCHEMY.SOL must contain the minimum time
in which the target substance can be obtained, or −1 if it cannot be
obtained at all.
Constraints
- 3 ≤ K ≤ 250, 3 ≤ N ≤ 500, 1 ≤ M < K
- sum of all reaction times ≤ 2·10⁹
Example
Input (ALCHEMY.DAT):
4 3 1 4
8
1 1
1 4
3
1 1
2 2 3
2
2 1 3
1 4
Output (ALCHEMY.SOL):
5
Substance 4 is obtained by running reaction 2 for the first 3 time units, then reaction 3 for 2 more — 5 units of time in total.
Solution idea
This is a discrete-event simulation over an AND/OR hypergraph rather than a plain shortest-path problem, since a reaction only fires once all of its inputs are ready. At each step, every reaction whose inputs are already available gets scheduled, tentatively giving each of its outputs a completion time; the simulation then jumps forward to the earliest such tentative time, "locks in" every substance that becomes ready at that instant, and repeats. This continues until the target substance locks in, no further substance becomes ready, or every reaction has fired — which finds the true minimum completion time because substances are only ever finalized in non-decreasing order of readiness, exactly like Dijkstra's algorithm processing nodes in order of shortest distance.