#ARC149B. [ARC149B] Two LIS Sum

[ARC149B] Two LIS Sum

Score : 500500 points

Problem Statement

For a sequence P=(P1,,PN)P = (P_1, \ldots, P_N), let LIS(P)\mathrm{LIS}(P) denote the length of a longest increasing subsequence.

You are given permutations A=(A1,,AN)A = (A_1, \ldots, A_N) and B=(B1,,BN)B = (B_1, \ldots, B_N) of integers from 11 through NN. You may perform the following operation on these sequences any number of times (possibly zero).

  • Choose an integer ii such that 1iN11\leq i\leq N-1. Swap AiA_i and Ai+1A_{i+1}, and swap BiB_i and Bi+1B_{i+1}.

Find the maximum possible final value of LIS(A)+LIS(B)\mathrm{LIS}(A) + \mathrm{LIS}(B).

What is a longest increasing subsequence?

A subsequence of a sequence is a sequence obtained by removing zero or more elements from the original sequence and then concatenating the remaining elements without changing the order. For instance, (10,30)(10,30) is a subsequence of (10,20,30)(10,20,30), but (20,10)(20,10) is not a subsequence of (10,20,30)(10,20,30).

A longest increasing subsequence of a sequence is a subsequence of that sequence with the greatest length among its subsequences that are strictly increasing.

Constraints

  • 2N3×1052\leq N\leq 3\times 10^5
  • 1AiN1\leq A_i\leq N
  • 1BiN1\leq B_i\leq N
  • AiAjA_i\neq A_j and BiBjB_i\neq B_j, if iji\neq j.

Input

The input is given from Standard Input in the following format:

NN

A1A_1 \ldots ANA_N

B1B_1 \ldots BNB_N

Output

Print the maximum possible final value of LIS(A)+LIS(B)\mathrm{LIS}(A) + \mathrm{LIS}(B).

5
5 2 1 4 3
3 1 2 5 4
8

Here is one way to achieve LIS(A)+LIS(B)=8\mathrm{LIS}(A) + \mathrm{LIS}(B) = 8.

  • Do the operation with i=2i = 2. Now, A=(5,1,2,4,3)A = (5,1,2,4,3), B=(3,2,1,5,4)B = (3,2,1,5,4).
  • Do the operation with i=1i = 1. Now, A=(1,5,2,4,3)A = (1,5,2,4,3), B=(2,3,1,5,4)B = (2,3,1,5,4).
  • Do the operation with i=4i = 4. Now, A=(1,5,2,3,4)A = (1,5,2,3,4), B=(2,3,1,4,5)B = (2,3,1,4,5).

Here, AA has a longest increasing subsequence (1,2,3,4)(1,2,3,4), so LIS(A)=4\mathrm{LIS}(A)=4, and BB has a longest increasing subsequence (2,3,4,5)(2,3,4,5), so LIS(B)=4\mathrm{LIS}(B)=4.

5
1 2 3 4 5
1 2 3 4 5
10

You can decide not to perform the operation at all to achieve LIS(A)+LIS(B)=10\mathrm{LIS}(A) + \mathrm{LIS}(B) = 10.