#P8268. [USACO22OPEN] Alchemy B

[USACO22OPEN] Alchemy B

Problem Description

Bessie the cow, who is always eager to develop new hobbies, is learning how to transmute metals. For 1iN1001 \le i \le N \le 100, she has aia_i (0ai1040 \le a_i \le 10^4) units of metal ii. In addition, she knows KK (1K<N1 \le K < N) recipes. Using a recipe, she can fuse one unit of each of several metals to produce one unit of a metal whose index is greater than all fused metals. It is also guaranteed that for each metal, Bessie knows at most one recipe to produce that metal.

Compute the maximum number of units of metal NN that Bessie can have after performing a sequence of transmutations.

Input Format

The first line contains NN.

The second line contains NN integers aia_i.

The third line contains KK.

The next KK lines each contain two integers LL and MM (M1M \ge 1), followed by MM integers. The last MM integers describe the metals that must be fused to produce one unit of metal LL. The input guarantees that LL is greater than these MM numbers.

Output Format

Output the maximum number of units of metal NN that Bessie can have after applying a sequence of zero or more transmutations.

5
2 0 0 1 0
3
5 2 3 4
2 1 1
3 1 2
1

Hint

[Sample Explanation]

In this example, one optimal sequence of transmutations is as follows:

  • Transmute one unit of metal 1 into metal 2.
  • Transmute one unit of metal 2 into metal 3.
  • Fuse one unit of metal 3 and one unit of metal 4 into metal 5.

Now Bessie has one unit of metal 1 and one unit of metal 5 left. She cannot make any more metal 5.

[Test Point Properties]

  • In test point 2, for 1i<N1 \le i < N, one unit of metal ii can be transmuted into one unit of metal i+1i+1.
  • In test points 3-4, each recipe converts one unit of a single metal into another metal.
  • Test points 5-11 have no additional restrictions.

Translated by ChatGPT 5