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 MBA company in the distant future builds balls. Each ball has N layers wrapped around each other like an onion, numbered from the innermost layer G1 to the outermost layer GN. Each layer has a type between 1 and L.
There are F 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 means the factory cannot do that job.
Production runs from the innermost layer G1 to the outermost layer GN. When two consecutive layers are built at different factories, the ball is moved between them and the transfer cost C applies. Two consecutive layers built at the same factory need no transfer. Recycling runs in reverse, from the outermost layer GN down to the innermost layer G1, 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.
The first line holds the number of factories F and the number of layer types L (1≤F≤500, 1≤L≤500). Factories are numbered 1 to F and layer types 1 to L.
The next 3F lines describe the factories, three lines per factory. The first line for factory f holds F integers Cf,1,Cf,2,…,Cf,F (0≤Cf,i≤103). Cf,i is the cost of moving the ball from factory f to factory i. The second line holds L integers D1,D2,…,DL (−1≤Di≤103). Di is the cost of producing one layer of type i at this factory, and −1 means production is impossible. The third line holds L integers R1,R2,…,RL (−1≤Ri≤103). Ri is the cost of recycling one layer of type i at this factory, and −1 means recycling is impossible.
The last line describes the ball. It starts with the layer count N (1≤N≤500), followed by N integers G1,G2,…,GN listing the type of each layer from the inside out (1≤Gi≤L).
Print one integer: the smallest possible sum of production and recycling costs.
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 G1 to GN, and recycling follows GN down to G1.