Why Did the Cow Cross the Road 8

Two rows each hold a permutation of N breeds; pair friendly pastures across the road without crossings to maximize the number of crosswalks.

Medium7Dynamic programmingIntervalsSortingNo attempts yetTime limit2sMemory limit512 MB

Problem

Farmer John (a different John from the one we have been helping so far) has NN breeds of cows on his farm, numbered breed 1, breed 2, ..., breed NN (1N10001 \le N \le 1000). Cows of breed aa and breed bb are friendly if ab4|a-b| \le 4, and unfriendly otherwise.

A straight road runs through the farm, with NN pastures on each side. Each pasture on the left side holds one breed of cow, and every breed appears in exactly one left pasture. The right side is arranged the same way. To prevent traffic accidents, John wants to build crosswalks. Each crosswalk connects one pasture on the left side to one pasture on the right side, and it does not have to be perpendicular to the road. A crosswalk may only connect two pastures whose cows are friendly. Each pasture may have at most one crosswalk, and no two crosswalks may cross each other.

Find the maximum number of crosswalks John can build.

Input

The first line contains NN. Each of the next NN lines gives the breed number of the cows in the pastures on the left side of the road, in order. Every breed appears exactly once. The following NN lines describe the pastures on the right side of the road in the same way.

Output

Print the maximum number of crosswalks that can be built under these rules.