Why Did the Cow Cross the Road 11
Time limit2sMemory limit512 MB
Given a permutation of breeds on each side of a road, connect pairs whose breed numbers differ by at most 4 using non-crossing edges, maximizing the count.
- Level
Hard8 of 10
- Topics
- Dynamic programming, Divide and conquer, Sorting, Segment tree
- Solved
- No attempts yet
Problem
We found a way to solve John's problem, but we got lost on the way to tell him. We did reach John's farm, yet instead of pastures there was an grid. It turned out we had visited the farm of a different man with the same name. Meanwhile, the John we wanted to help kept getting wrong-answer and runtime-error verdicts no matter how much he debugged his code, so he gave up and is now trying a second plan.
John recently learned that some breeds are friendly with each other. His farm has breeds of cows, numbered breed 1, breed 2, ..., breed . Cows of breed and breed are friendly if ; otherwise they do not get along.
For the new members of the Help John Association, here is the layout of the farm again. A straight road runs through the farm, with pastures on each side. On the left side, each breed occupies exactly one pasture, and the same holds on the right side. To prevent traffic accidents, John wants to build crosswalks. Each crosswalk connects one pasture on the left with one pasture on the right, and it does not need to be perpendicular to the road. A crosswalk may only connect two pastures whose cows are friendly. Each pasture can have at most one crosswalk, and no two crosswalks may cross.
Help John build as many crosswalks as possible under these rules.
Input
The first line contains (). Each of the next lines gives the breed number of the cows in the pastures on the left side of the road, in order. Each breed appears exactly once. The following 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 while satisfying the conditions.