The longest common increasing subsequence

3.1

7 votes
Algorithms, Dynamic Programming, 2D dynamic programming, Divide-and-conquer algorithm, C++
Problem

You are given two sequences of numbers named A and B. Your task is to find the longest common increasing subsequence.

In other words, let us assume that A has the length of n and can be shown as A1,A2,...,An. Also, B has the length of m and can be shown as B1,B2,...,Bm.

You are required to find a number l and two sequences of indices named C and D of length l such that the following conditions hold:

  • 1C1<C2<...<Cln
  • 1D1<D2<...<Dlm
  • For each 1il, you are given ACi=BDi (common subsequence condition)
  • AC1AC2...ACl (increasing subsequence condition)
  • BD1BD2...BDl (increasing subsequence condition)

Input format

  • The first line contains two integers n and m respectively where n is the length of sequence A and m is the length for B.
  • The second line contains n space-separated integers that represent the elements of the sequence A.
  • The third line contains m space-separated integers that represent the elements of the sequence B.

Output format

The output contains three lines:

In the first line, print an integer l that denotes the length of the longest common increasing subsequence.

In the second line, print l integers that represent elements of C (chosen indices of subsequence from A).

In the third line, print l integers that represent elements of D (chosen indices of subsequence from B).

Note

  • The elements of C and D must be in increasing order.
  • The answer to the problem could be 0, in this case, you just need to print 0 in a single line.

Constraints

1n,m105

1Ai,Bi109

Time Limit: 2
Memory Limit: 256
Source Limit:
Explanation

As you can see, A1=B1 and A4=B2, A1A4 and B1B2. So this is a common increasing subsequence. However, this is not the best possible.

Consider the following indices from A and B:

  • C = {1, 3, 4}
  • D = {1, 4, 5}

Since following condition hold:

  • A1=B1, A3=B4 and A4=B5
  • A1A3A4
  • B1B4B5

 

this is also a common increasing subsequence with length 3.

Editor Image

?