using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static string InputPattern = "InputX";
static List<string> GetInputList()
{
var WillReturn = new List<string>();
if (InputPattern == "Input1") {
WillReturn.Add("5");
WillReturn.Add("5 2 1 4 3");
WillReturn.Add("3 1 2 5 4");
//8
}
else if (InputPattern == "Input2") {
WillReturn.Add("5");
WillReturn.Add("1 2 3 4 5");
WillReturn.Add("1 2 3 4 5");
//10
}
else {
string wkStr;
while ((wkStr = Console.ReadLine()) != null) WillReturn.Add(wkStr);
}
return WillReturn;
}
static void Main()
{
List<string> InputList = GetInputList();
int[] AArr = InputList[1].Split(' ').Select(pX => int.Parse(pX)).ToArray();
int[] BArr = InputList[2].Split(' ').Select(pX => int.Parse(pX)).ToArray();
var AnswerKouhoList = new List<int>();
AnswerKouhoList.Add(AnswerKouho(AArr, BArr));
AnswerKouhoList.Add(AnswerKouho(BArr, AArr));
Console.WriteLine(AnswerKouhoList.Max());
}
static int AnswerKouho(int[] pAArr, int[] pBArr)
{
// 配列Bの値[配列Aの値]
var BValDict = new Dictionary<int, int>();
for (int I = 0; I <= pAArr.GetUpperBound(0); I++) {
BValDict[pAArr[I]] = pBArr[I];
}
int[] SortedAArr = pAArr.OrderBy(pX => pX).ToArray();
var BList = new List<int>();
foreach (int EachA in SortedAArr) {
BList.Add(BValDict[EachA]);
}
int AnswerKouho = SortedAArr.Length + DeriveLISLen(BList);
return AnswerKouho;
}
// 列挙を引数として、LISの長さを返す
static int DeriveLISLen(IEnumerable<int> pEnum)
{
// LISの最終値の最小値[LISの長さ] なDP表
var DPSortedList = new SortedList<int, int>();
foreach (int EachA in pEnum) {
if (DPSortedList.Count == 0) {
DPSortedList[1] = EachA;
continue;
}
int UpsertKeyInd = ExecNibunhou(DPSortedList, EachA);
int CurrUB = DPSortedList.Count - 1;
var Keys = DPSortedList.Keys;
// 更新する位置によって分岐
if (UpsertKeyInd <= CurrUB) {
DPSortedList[Keys[UpsertKeyInd]] = EachA;
}
else {
int PrevKey = Keys[CurrUB];
DPSortedList[PrevKey + 1] = EachA;
}
}
return DPSortedList.Keys.Max();
}
// 二分法で、引数の値を設定する、キーの配列の添字を返す
static int ExecNibunhou(SortedList<int, int> pDPSortedList, int pTargetVal)
{
int UB = pDPSortedList.Count - 1;
var Keys = pDPSortedList.Keys;
// 最小値以下の場合
if (pTargetVal <= pDPSortedList[Keys[0]]) {
return 0;
}
// 最大値より大きい場合
if (pTargetVal > pDPSortedList[Keys[UB]]) {
return UB + 1;
}
int L = 0;
int R = UB;
while (L + 1 < R) {
int Mid = (L + R) / 2;
if (pDPSortedList[Keys[Mid]] < pTargetVal) {
L = Mid;
}
else {
R = Mid;
}
}
return R;
}
}