Match boxes and toys from two run-length encoded lines in order to maximize the number of equal-type pairs.
Medium6Dynamic programmingNo attempts yetTime limit5sMemory limit512 MBYou run a factory with two assembly lines. The first line makes boxes, and the second line makes the toys that go into those boxes. Each box type takes exactly one toy type, and each toy type fits exactly one box type.
At the start you pick up a box from the first line and a toy from the second line. While you hold one box and one toy, you can do one of the following.
You pick up boxes in the order they were made, and you pick up toys in the order they were made. Given the production order of both lines, find the largest number of boxed toys you can send out.
The two lines make a great many boxes and toys. Each line keeps making one type for a long stretch before it switches to another type, so the production order is given as runs of one type.
The first line contains the number of test cases T. Each test case takes three lines.
The first line contains two integers N and M. The second line contains 2N integers a1, A1, a2, A2, ..., aN, AN. The third line contains 2M integers b1, B1, b2, B2, ..., bM, BM.
The first line makes a1 boxes of type A1, then a2 boxes of type A2, and finally aN boxes of type AN. In the same way, the second line makes b1 toys of type B1 through bM toys of type BM. A toy goes into a box if and only if their type numbers are equal.
Two neighboring runs can have the same type number.
For each test case, print one line in the form "Case #x: y", where x is the test case number starting from 1 and y is the largest number of boxed toys you can send out.