Fenced In (Platinum)
Farmer John has realized that many of his cows are strangely agoraphobic (being fearful of large open spaces). To try and make them less afraid of grazing, he partitions his large field into a number of smaller regions by building vertical (north-south) and horizontal (east-west) fences.
The large field is a rectangle with corner points at (0, 0) and (a, b). FJ builds n vertical fences at distinct locations a[1]
... a[n]
(0 < a[i]
< a); each fence runs from (a[i]
, 0) to (a[i]
, b). He also builds m horizontal fences at locations b[1]
... b[m]
(0 < b[i]
< b); each such fence runs from (0, b[i]
) to (a, b[i]
). Each vertical fence crosses through each horizontal fence, subdividing the large field into a total of (n + 1) (m + 1) regions.
Unfortunately, FJ completely forgot to build gates into his fences, making it impossible for cows to leave their enclosing region and travel around the entire field! He wants to remedy this situation by removing pieces of some of his fences to allow cows to travel between adjacent regions. He wants to select certain pairs of adjacent regions and remove the entire length of fence separating them; afterwards, he wants cows to be able to wander through these openings so they can travel anywhere in his larger field.
For example, FJ might take a fence pattern looking like this:
+---+--+ | | | +---+--+ | | | | | | +---+--+
and open it up like so:
+---+--+ | | +---+ + | | | | +---+--+
Please help FJ determine the minimum total length of fencing he must remove to accomplish his goal.
Input
The first line contains a, b (1 ≤ a, b ≤ 10^9
), n (0 ≤ n ≤ 25000) and m (0 ≤ m ≤ 25000). The next n lines contain a[1]
... a[n]
, and the next m lines after that contain b[1]
... b[m]
.
Output
Write the minimum length of fencing FJ must remove. Note that this might be too large to fit into a standard 32-bit integer, so you may need to use 64-bit integer types.