PHƯỚC HƯNG OJ · THỬ THÁCH THUẬT TOÁN

#FT0000093. Băng qua đường không giao nhau II (Why Did the Cow Cross the Road II)

HỌC THEO LỘ TRÌNH

Bài tập thuộc lộ trình

2 lộ trình

Băng qua đường không giao nhau II (Why Did the Cow Cross the Road II)

Why Did the Cow Cross the Road II

Source: USACO

Version: Phuoc Hung OJ Extended

Problem Statement

There are two ordered sequences of nn fields on opposite sides of a road. Each field is designated for a cow breed with an ID from 11 to nn. On each side, every breed ID appears exactly once.

The farmer wants to draw crosswalks, each connecting one field on one side to one field on the other. Breeds xx and yy are friendly exactly when ∣x−y∣≤4|x-y|\le4. A crosswalk may connect only friendly breeds.

Crosswalks must not intersect each other in the interior of the road. Also, each field may serve as an endpoint of at most one crosswalk.

Find the maximum number of crosswalks. The ordering of fields on both sides is fixed and cannot be rearranged.

Input

The first line contains nn. Each of the next nn lines gives a breed ID on the first side in order. Each of the last nn lines gives a breed ID on the second side in the same direction. Each group of nn IDs is a permutation of 1,2,…,n1,2,\ldots,n.

Output

Print one integer: the maximum number of friendly, pairwise noncrossing crosswalks with distinct endpoints.

Subtasks

  • Subtask 1 (20 points): 1≤n≤101\le n\le10; both sequences are permutations of 1,2,…,n1,2,\ldots,n, with each ID occurring once per side.
  • Subtask 2 (30 points): 1≤n≤20001\le n\le2000; both sequences are permutations of 1,2,…,n1,2,\ldots,n, with each ID occurring once per side.
  • Subtask 3 (50 points): 1≤n≤1051\le n\le10^5; both sequences are permutations of 1,2,…,n1,2,\ldots,n, with each ID occurring once per side.

Examples

Example 1

Input

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

Output

5

Explanation

The first side is 1,2,3,4,5,61,2,3,4,5,6 and the second is 6,5,4,3,2,16,5,4,3,2,1. Connect the first five fields on the first side to the last five fields on the second: the paired breed IDs are (1,5),(2,4),(3,3),(4,2),(5,1)(1,5),(2,4),(3,3),(4,2),(5,1). All differences are at most 44, and the pairings preserve position order, so no crosswalks intersect. Six crosswalks would pair (1,6)(1,6) at the first positions, but ∣1−6∣=5|1-6|=5; thus the maximum is 55.

Example 2

Input

1
1
1

Output

1

Explanation

Each side has one field of breed 11. The difference is 0≤40\le4, so one crosswalk is valid. No second crosswalk is possible because there are no other endpoints.