Super Ball

Choose a factory for each layer in the production order and again in the recycling order, minimizing layer costs plus transfer costs C whenever consecutive layers use different factories.

Medium6Dynamic programmingGreedyNo attempts yetTime limit2sMemory limit512 MB

Problem

A company in the distant future builds balls. Each ball has NN layers wrapped around each other like an onion, numbered from the innermost layer G1G_1 to the outermost layer GNG_N. Each layer has a type between 11 and LL.

There are FF factories. Each factory can build only certain layer types. One factory can handle several types, and one type can be handled by several factories. Building a layer at a factory costs the production price of that factory, and taking a layer apart at a factory costs its recycling price. A price of 1-1 means the factory cannot do that job.

Production runs from the innermost layer G1G_1 to the outermost layer GNG_N. When two consecutive layers are built at different factories, the ball is moved between them and the transfer cost CC applies. Two consecutive layers built at the same factory need no transfer. Recycling runs in reverse, from the outermost layer GNG_N down to the innermost layer G1G_1, with the same transfer rule. Pickup of the finished ball and return of the used ball are free from any factory. Choose factories for every layer in both directions so the sum of production and recycling costs is as small as possible.

Input

The first line holds the number of factories FF and the number of layer types LL (1F5001 \le F \le 500, 1L5001 \le L \le 500). Factories are numbered 11 to FF and layer types 11 to LL.

The next 3F3F lines describe the factories, three lines per factory. The first line for factory ff holds FF integers Cf,1,Cf,2,,Cf,FC_{f,1}, C_{f,2}, \dots, C_{f,F} (0Cf,i1030 \le C_{f,i} \le 10^3). Cf,iC_{f,i} is the cost of moving the ball from factory ff to factory ii. The second line holds LL integers D1,D2,,DLD_1, D_2, \dots, D_L (1Di103-1 \le D_i \le 10^3). DiD_i is the cost of producing one layer of type ii at this factory, and 1-1 means production is impossible. The third line holds LL integers R1,R2,,RLR_1, R_2, \dots, R_L (1Ri103-1 \le R_i \le 10^3). RiR_i is the cost of recycling one layer of type ii at this factory, and 1-1 means recycling is impossible.

The last line describes the ball. It starts with the layer count NN (1N5001 \le N \le 500), followed by NN integers G1,G2,,GNG_1, G_2, \dots, G_N listing the type of each layer from the inside out (1GiL1 \le G_i \le L).

Output

Print one integer: the smallest possible sum of production and recycling costs.

Hint

Pickup and return are free, so production and recycling do not affect each other. The answer is the smallest production cost plus the smallest recycling cost. Each part is a dynamic program over the layer order: production follows G1G_1 to GNG_N, and recycling follows GNG_N down to G1G_1.