Crossed Matchings
Time limit1sMemory limit128 MB
Given two rows of positive integers, draw the maximum number of equal-value matching segments between the rows so that each segment crosses exactly one other and no number is used twice.
- Level
Hard8 of 10
- Topics
- Dynamic programming, Array, Two pointers, Combinatorics
- Solved
- No attempts yet
Problem
Positive integers are listed in two rows. If two equal numbers lie in different rows — one in the first row and the other in the second row — we may connect them with a single line segment. If the value of such a segment is , we call it an -matching segment. The figure below shows a 3-matching segment and a 2-matching segment.

For the given input, we want to draw as many matching segments as possible so that all of the following hold:
- Every -matching segment must cross exactly one -matching segment, where .
- No number may be an endpoint of more than one segment (each number is used by at most one segment). For example, the matchings shown below are not allowed.

Write a program that computes the maximum number of matching segments. Note that this number is always even.
Input
The first line contains the number of test cases (). Each test case consists of three lines. The first line contains and , the number of integers in the first and the second row, respectively. The next line contains the integers of the first row, and the following line contains the integers of the second row. All numbers are positive integers less than .
Output
For each test case, print the maximum number of matching segments on its own line.