Under construction

Still being built. Things may change

Joining Arrays

Time limit4sMemory limit512 MB

Summary
Find the lexicographically smallest length-k array that splits into a non-empty subsequence of A and a non-empty subsequence of B, with positions interleaved.
Level

Medium7 of 10

Topics
Dynamic programming, Greedy, String
Solved
No attempts yet

Problem

Consider two arrays of integers A=[a1,a2,…,an]A = [a_1, a_2, \ldots, a_n] and B=[b1,b2,…,bm]B = [b_1, b_2, \ldots, b_m]. The kk-join of AA and BB is the lexicographically smallest array RR of length kk that can be split into two non-empty subsequences, where the first is a subsequence of AA and the second is a subsequence of BB.

Formally, you need to find the array R=[r1,r2,…,rk]R = [r_1, r_2, \ldots, r_k] for which there exist two non-empty index sequences 1≤i1,1<i1,2<…<i1,t≤n1 \le i_{1,1} < i_{1,2} < \ldots < i_{1,t} \le n and 1<j1,1<j1,2<…<j1,k−t≤m1 < j_{1,1} < j_{1,2} < \ldots < j_{1,k-t} \le m, and two index sequences 1≤i2,1<i2,2<…<i2,t≤k1 \le i_{2,1} < i_{2,2} < \ldots < i_{2,t} \le k and 1≤j2,1<j2,2<…<j2,k−t≤k1 \le j_{2,1} < j_{2,2} < \ldots < j_{2,k-t} \le k, such that:

  • For each 1≤p≤t1 \le p \le t and 1≤q≤k−t1 \le q \le k - t, we have i2,p≠j2,qi_{2,p} \ne j_{2,q}.
  • For each 1≤p≤t1 \le p \le t, we have ai1,p=ri2,pa_{i_{1,p}} = r_{i_{2,p}}.
  • For each 1≤p≤k−t1 \le p \le k - t, we have bj1,p=rj2,pb_{j_{1,p}} = r_{j_{2,p}}.

For example, if A=[1,2,1,3,1,2,1]A = [1, 2, 1, 3, 1, 2, 1], B=[1,2,3,1]B = [1, 2, 3, 1], and k=9k = 9, their kk-join is R=[1,1,1,1,2,1,2,3,1]R = [1, 1, 1, 1, 2, 1, 2, 3, 1] (the subsequence from the first array is [1,1,1,2,1][1, 1, 1, 2, 1], and the subsequence from the second array is [1,2,3,1][1, 2, 3, 1]).

For two given arrays AA and BB and an integer kk, find their kk-join RR.

Input

The first line contains nn, the length of array AA (1≤n≤30001 \le n \le 3000).

The second line contains nn integers aia_i, the elements of AA (1≤ai≤30001 \le a_i \le 3000).

The third line contains mm, the length of array BB (1≤m≤30001 \le m \le 3000).

The fourth line contains mm integers bib_i, the elements of BB (1≤bi≤30001 \le b_i \le 3000).

The last line contains the integer kk (2≤k≤n+m2 \le k \le n + m).

Output

Output the kk-join of the given arrays.

Examples1

  1. Example 1

    Input
    7
    1 2 1 3 1 2 1
    4
    1 2 3 1
    9
    
    Expected output
    1 1 1 1 2 1 2 3 1