Remove fence segments between adjacent field regions so every region connects with the smallest possible total removed length.
Medium7Minimum spanning treeGreedySortingNo attempts yetTime limit2sMemory limit512 MBFarmer John has noticed that many of his cows are agoraphobic, meaning they are afraid of large open spaces. To make grazing less frightening, he splits his large field into smaller regions by building vertical (north to south) and horizontal (east to west) fences.
The large field is a rectangle whose opposite corners are (0,0) and (A,B). John builds n vertical fences at distinct positions a1,…,an (0<ai<A); the fence at ai runs from (ai,0) to (ai,B). He also builds m horizontal fences at distinct positions b1,…,bm (0<bi<B); the fence at bi runs from (0,bi) to (A,bi). Every vertical fence crosses every horizontal fence, so the field is cut into (n+1)(m+1) regions.
John forgot to put gates in the fences, so a cow cannot leave the region it is standing in. He wants to fix this by removing parts of some fences. He picks pairs of adjacent regions and removes the entire stretch of fence that separates them, and he wants a cow to be able to reach every part of the field through those openings.
For example, John might start from this fence pattern.
+---+--+
| | |
+---+--+
| | |
| | |
+---+--+
He can open it up like this.
+---+--+
| |
+---+ +
| |
| |
+---+--+
Compute the minimum total length of fence John has to remove.
The first line contains A, B, n, and m (1≤A,B≤109, 0≤n≤25000, 0≤m≤25000). The next n lines contain a1,…,an, one per line. The m lines after that contain b1,…,bm, one per line. The ai are distinct and the bi are distinct.
Print the minimum total length of fence that must be removed. The answer can exceed the range of a 32-bit integer.