Why Did the Cow Cross the Road 12
Time limit2sMemory limit512 MB
Given the left and right orderings of N breeds along a road, count pairs whose segments cross and whose breed numbers differ by more than K.
- Level
Medium6 of 10
- Topics
- Divide and conquer, Sorting, Array, Binary search
- Solved
- No attempts yet
Problem
This time we found John's farm without trouble, but the plan still fell through for a different reason: someone found an error in his theory of cow friendliness.
John's farm has breeds of cows, numbered . Cows of breed and breed are friendly if , and unfriendly otherwise. Pastures for different breeds are built so differently that each pasture can hold only one specific breed: pasture can graze only cows of breed . When a cow crosses the road, it walks to the pasture on the other side that grazes its own breed.
For the new members of the Help John Association, here is the farm layout again. The farm has one straight road with pastures on each side. On the left side, each breed occupies exactly one pasture, and the same holds on the right side. John paid no attention to the order when he built the pastures, so the paths of a breed cow and a breed cow may cross each other. Call such a pair of breeds a "crossing pair".
Before installing crosswalks, we want to count the crossing pairs whose breeds are unfriendly. The term of the association's president is almost over, so this is our last task. Let's help John one last time.
Input
The first line contains () and (). Each of the next lines contains one pasture number, listing the pastures on the left side of the road in order. Every breed appears exactly once. The next lines list the pastures on the right side of the road in the same format.
Output
Print the number of crossing pairs whose breeds are unfriendly.
Hint
In the first example, breeds and , and breeds and , are the crossing pairs that are unfriendly.