Fenced In (Gold)

Remove fence segments of minimum total length so every region of the fenced grid connects to every other.

Medium7Minimum spanning treeGreedySortingNo attempts yetTime limit2sMemory limit512 MB

Problem

Farmer John has noticed that many of his cows are afraid of wide open spaces. To make grazing less frightening for them, he split his large field into smaller regions by building north to south (vertical) fences and east to west (horizontal) fences.

The field is a rectangle whose opposite corners are (0,0)(0,0) and (A,B)(A,B). Farmer John built nn vertical fences (0n20000 \le n \le 2000) at distinct positions a1,,ana_1, \ldots, a_n (0<ai<A0 < a_i < A), and the fence at aia_i runs from (ai,0)(a_i, 0) to (ai,B)(a_i, B). He also built mm horizontal fences (0m20000 \le m \le 2000) at distinct positions b1,,bmb_1, \ldots, b_m (0<bi<B0 < b_i < B), and the fence at bib_i runs from (0,bi)(0, b_i) to (A,bi)(A, b_i). Every vertical fence crosses every horizontal fence, so the field is cut into (n+1)(m+1)(n+1)(m+1) regions.

Farmer John forgot to put gates in his fences, so a cow cannot leave the region it stands in and walk around the whole field. He wants to fix that by removing pieces of some fences. He picks pairs of adjacent regions and removes the entire length of fence that separates them. After the removals a cow must be able to reach any region from any other region through the openings.

For example, a fence layout like this

+---+--+
|   |  |
+---+--+
|   |  |
|   |  |
+---+--+

can be opened up like this.

+---+--+
|      |
+---+  +
|      |
|      |
+---+--+

Find the minimum total length of fence Farmer John has to remove.

Input

The first line has AA, BB, nn, and mm (1A,B1091 \le A, B \le 10^9). Each of the next nn lines has one of a1,,ana_1, \ldots, a_n, and each of the mm lines after that has one of b1,,bmb_1, \ldots, b_m.

Output

Print the minimum total length of fence Farmer John has to remove. The answer can exceed the range of a 32-bit integer, so you may need a 64-bit integer type (long long in C or C++, for example).