Super Ball
Time limit2sMemory limit512 MB
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.
- Level
Medium6 of 10
- Topics
- Dynamic programming, Greedy
- Solved
- No attempts yet
Problem
A company in the distant future builds balls. Each ball has layers wrapped around each other like an onion, numbered from the innermost layer to the outermost layer . Each layer has a type between and .
There are 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 means the factory cannot do that job.
Production runs from the innermost layer to the outermost layer . When two consecutive layers are built at different factories, the ball is moved between them and the transfer cost applies. Two consecutive layers built at the same factory need no transfer. Recycling runs in reverse, from the outermost layer down to the innermost layer , 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 and the number of layer types (, ). Factories are numbered to and layer types to .
The next lines describe the factories, three lines per factory. The first line for factory holds integers (). is the cost of moving the ball from factory to factory . The second line holds integers (). is the cost of producing one layer of type at this factory, and means production is impossible. The third line holds integers (). is the cost of recycling one layer of type at this factory, and means recycling is impossible.
The last line describes the ball. It starts with the layer count (), followed by integers listing the type of each layer from the inside out ().
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 to , and recycling follows down to .