#P6171. [USACO16FEB] Fenced In G

[USACO16FEB] Fenced In G

Description

Farmer John realized that his cows have recently developed a phobia (fear of overly open spaces). To reduce their fear while grazing, FJ decided to build some horizontal and vertical fences to divide the pasture into several smaller regions.

The whole pasture is a rectangle, with two corners at (0,0)(0,0) and (A,B)(A,B). FJ builds nn vertical fences at nn distinct positions a1,,ana_1,\ldots,a_n. Each fence goes from (ai,0)(a_i,0) to (ai,B)(a_i,B). FJ also builds mm horizontal fences at mm distinct positions b1,,bmb_1,\ldots,b_m. Each fence goes from (0,bi)(0,b_i) to (A,bi)(A,b_i). The vertical and horizontal fences intersect each other, splitting the entire pasture into (n+1)(m+1)(n+1)(m+1) regions.

Unfortunately, FJ forgot to put gates in the fences, so each cow is trapped in a small region. He wants to fix this by removing some fences. Each time, he can choose two adjacent regions and remove the fence segment separating them. FJ's goal is to make it possible for the cows to reach any place in the pasture.

Here is an example:

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

After removing some fences, it becomes:

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

To reduce the amount of work, FJ of course wants the total length of removed fences to be as small as possible.

Input Format

The first line contains four integers A,B,n,mA, B, n, m. It is guaranteed that 1n,m20001 \leq n, m \leq 2000 and 1A,B1091 \leq A, B \leq 10^9.

The next nn lines each contain an integer aia_i, with 0<ai<A0 < a_i < A.

The next mm lines each contain an integer bib_i, with 0<bi<B0 < b_i < B.

Output Format

Output the minimum total length of fences to remove. The answer must be stored in a 64-bit signed integer.

15 15 5 2
2
5
10
6
4
11
3
44

Hint

Translated by ChatGPT 5