#FT0000093. Băng qua đường không giao nhau II (Why Did the Cow Cross the Road II)
Bài tập thuộc lộ trình
Mục lục đề ⌄
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 fields on opposite sides of a road. Each field is designated for a cow breed with an ID from to . 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 and are friendly exactly when . 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 . Each of the next lines gives a breed ID on the first side in order. Each of the last lines gives a breed ID on the second side in the same direction. Each group of IDs is a permutation of .
Output
Print one integer: the maximum number of friendly, pairwise noncrossing crosswalks with distinct endpoints.
Subtasks
- Subtask 1 (20 points): ; both sequences are permutations of , with each ID occurring once per side.
- Subtask 2 (30 points): ; both sequences are permutations of , with each ID occurring once per side.
- Subtask 3 (50 points): ; both sequences are permutations of , 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 and the second is . Connect the first five fields on the first side to the last five fields on the second: the paired breed IDs are . All differences are at most , and the pairings preserve position order, so no crosswalks intersect. Six crosswalks would pair at the first positions, but ; thus the maximum is .
Example 2
Input
1
1
1
Output
1
Explanation
Each side has one field of breed . The difference is , so one crosswalk is valid. No second crosswalk is possible because there are no other endpoints.