#K93177. Intersection of Two Lists Preserving Order with Duplicates

    ID: 38362 Type: Default 1000ms 256MiB

Intersection of Two Lists Preserving Order with Duplicates

Intersection of Two Lists Preserving Order with Duplicates

Given two lists of integers, the task is to compute the intersection of these two lists. The intersection should be constructed by preserving the order of elements as they appear in the first list and by retaining duplicate occurrences. In other words, for each element in the first list, if it appears in the second list (taking into account the frequency of occurrence), it should be included in the output.

The mathematical formulation can be interpreted as follows: \( A \cap B = \{ x \mid x \in A \text{ and } count_A(x) \leq count_B(x) \} \), where the order is preserved according to list A.

inputFormat

The first line of the input contains a single integer \(T\) denoting the number of test cases. Each test case consists of two lines:

  • The first line begins with an integer \(n\) (the number of elements in the first list) followed by \(n\) space-separated integers.
  • The second line begins with an integer \(m\) (the number of elements in the second list) followed by \(m\) space-separated integers.

Input is read from standard input (stdin).

outputFormat

For each test case, output a single line containing the intersection of the two lists. The result should list the elements (if any) separated by spaces in the order they appear in the first list, with duplicates retained as described. If the intersection is empty, output an empty line.

Output is written to standard output (stdout).

## sample
1
5 1 2 2 3 4
4 2 3 2 5
2 2 3

</p>