Cooking Courses
Time limit2sMemory limit512 MB
Choose an academy for each of M courses in order, keeping each academy run between S and E long, avoiding one forbidden switch per academy, and paying a switch fee, to minimize total cost.
- Level
Medium7 of 10
- Topics
- Dynamic programming, Sliding window, Greedy, Implementation
- Solved
- No attempts yet
Problem
To earn a cooking certificate you must take courses, course 1 through course , in that order and exactly once each. The courses are offered by academies, and the fee for the same course can differ from academy to academy.
The table below shows example fees for and .
You may switch academies partway to cut the cost. Each switch adds a fee of . A switch must obey the two rules below.
Rule (a). The number of courses taken consecutively at one academy is at least and at most . The academy where you take course is exempt from the lower bound . The upper bound still applies there.
Suppose and . If you take course 1 at academy 1, course 2 must also be taken at academy 1, while course 3 may be taken at academy 1 or at another academy. If you take courses 1 through 3 at academy 1, course 4 must be taken at another academy. With and it is possible to take courses 1 and 2 at academy 3, courses 3 and 4 at academy 1, and course 5 at academy 3 again.
Rule (b). Every academy has exactly one disallowed academy. If the disallowed academy of academy is academy , you cannot switch from academy to academy .
In the table below the disallowed academy of academy 1 is academy 2, so switching straight from academy 2 to academy 1 is impossible. Moving through another academy, as in academy 2 → academy 4 → academy 1, is possible.
Suppose , , , and the two tables above. Reading the academy numbers in course order:
- 1 → 1 → 1 → 1 → 3 takes four courses in a row at one academy, which breaks rule (a).
- 2 → 2 → 1 → 1 → 1 switches from academy 2 to academy 1, which breaks rule (b).
- 3 → 3 → 1 → 1 → 3 is allowed, and the total cost is .
- 1 → 1 → 1 → 3 → 3 is allowed, and the total cost is .
Given the fees and the disallowed academies, find the minimum cost of taking all courses in order.
Input
The first line contains the number of academies , the number of courses , the minimum number and the maximum number of courses that can be taken consecutively at one academy, and the switching fee , separated by spaces. (, , , , )
Each of the next lines contains the fees of one academy. The -th of these lines contains integers, the fees of academy for course 1 through course , separated by spaces. Each fee is an integer between and .
Each of the next lines contains the number of the disallowed academy of academy 1 through academy , one per line. Each number is between and and differs from the number of the academy itself.
Output
Print the minimum cost on the first line.