#P6119. Non-Crossing Cow Crosswalks

    ID: 19341 Type: Default 1000ms 256MiB

Non-Crossing Cow Crosswalks

Non-Crossing Cow Crosswalks

Farmer John has N breeds of cows, numbered from \(1\) to \(N\). Each breed appears exactly once on each side of a long road. The left side has \(N\) pastures and the right side has \(N\) pastures, with one cow breed in each pasture. Two breeds \(a\) and \(b\) are friendly if and only if \(|a-b| \leq 4\) (in \(\LaTeX\) format, the condition is \(|a-b| \leq 4\)).

Farmer John wishes to draw some crosswalks (each connecting one pasture on the left with one on the right) to help the cows cross the road safely. The crosswalks must satisfy the following conditions:

  1. Each crosswalk connects a pasture on the left to a pasture on the right.
  2. The two breeds on the connected pastures must be friendly (i.e. if the breeds are \(a\) and \(b\), then \(|a-b| \leq 4\)).
  3. The crosswalks must not cross each other. That is, if the left pastures are connected in order \(i_1, i_2, \dots, i_k\) and the corresponding connected right pastures are \(j_1, j_2, \dots, j_k\), then it must hold that \(j_1 < j_2 < \cdots < j_k\).
  4. Each pasture can be connected by at most one crosswalk.

Your task is to determine the maximum number of crosswalks that Farmer John can draw.

Input and Output: The input begins with an integer \(N\). The next \(N\) lines contain the breeds in the left pastures in order, and the following \(N\) lines contain the breeds in the right pastures in order. The output is a single integer, the maximum number of crosswalks that can be constructed.

inputFormat

The first line of input contains a single integer \(N\) (the number of cow breeds and pastures on each side). The next \(N\) lines each contain one integer indicating the cow breed in the corresponding left pasture. The following \(N\) lines each contain one integer indicating the cow breed in the corresponding right pasture.

Example:

5
1
2
3
4
5
1
2
3
4
5

outputFormat

Output a single integer: the maximum number of non-crossing crosswalks that can be drawn satisfying the friendship condition \(|a-b| \leq 4\).

Example:

5

sample

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