Chip Cards
Time limit2sMemory limit16 MB
Given the bottom port order and socket sizes on both boundaries, find the maximum number of layers needed when each socket can be reversed.
- Level
Hard8 of 10
- Topics
- Dynamic programming, Array, Intervals
- Solved
- No attempts yet
Statement
Johnny designs chips for chip cards. Each chip has ports on its upper boundary and ports on its bottom boundary. The upper ports are labelled from left to right as . The bottom ports carry the same labels, also from left to right, but in a possibly different order. A pair of ports with the same label is joined by a straight-line path. The paths are grouped into layers, and paths in the same layer cannot cross.
The ports on each boundary are grouped into sockets. Each socket is a run of consecutive ports, and every port belongs to exactly one socket. The bottom sockets may have different lengths than the upper sockets. A socket can be switched, which reverses the order of the ports inside it.
Johnny has heard that he is going to be fired. He wants a small revenge, so he will design the next chip to be as expensive to produce as possible. The main production cost is the number of layers, so he switches each socket in the way that maximises the number of layers needed. This is harder than his usual work, and Johnny needs your help.
Input
The first line contains a positive integer (), the number of ports on each boundary. The second line contains distinct integers from , the labels of the bottom ports in order. The third line starts with an integer (), the number of upper sockets, followed by integers giving the number of ports in each consecutive upper socket. Each socket has at least one port, and the upper socket sizes sum to . The fourth line describes the bottom sockets in the same format.
Output
Print one positive integer, the maximum possible number of layers needed.
Hint
The first upper socket contains ports , the second contains port , and the third contains ports . By switching the sockets, the upper boundary can show these orders: