Longest Common Increasing Subsequence

No attempts yetTime limit1sMemory limit256 MB

Problem

You are given two sequences of integers, AA and BB. Write a program that finds the length of the longest common increasing subsequence of the two sequences.

A sequence S1,S2,,SkS_1, S_2, \dots, S_k is an increasing subsequence of a sequence X1,X2,,XLX_1, X_2, \dots, X_L when both of the following hold.

  • There exist indices 1i1<i2<<ikL1 \le i_1 < i_2 < \dots < i_k \le L such that Sj=XijS_j = X_{i_j} for every jj. In other words, SS is a subsequence of XX.
  • Sj<Sj+1S_j < S_{j+1} for every 1j<k1 \le j < k. In other words, SS is strictly increasing.

A common increasing subsequence is a sequence that is an increasing subsequence of both AA and BB.

Input

The two sequences are given over two lines each.

  • The first line contains the length NN of the first sequence. (1N5001 \le N \le 500)
  • The second line contains its elements A1,A2,,ANA_1, A_2, \dots, A_N separated by spaces. (231Ai<231-2^{31} \le A_i < 2^{31})
  • The third line contains the length MM of the second sequence. (1M5001 \le M \le 500)
  • The fourth line contains its elements B1,B2,,BMB_1, B_2, \dots, B_M separated by spaces. (231Bi<231-2^{31} \le B_i < 2^{31})

Output

Print a single integer: the length of the longest common increasing subsequence. If no common increasing subsequence exists, print 00.