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 MBFarmer 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) and (A,B). Farmer John built n vertical fences (0≤n≤2000) at distinct positions a1,…,an (0<ai<A), and the fence at ai runs from (ai,0) to (ai,B). He also built m horizontal fences (0≤m≤2000) at distinct positions b1,…,bm (0<bi<B), and 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.
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.
The first line has A, B, n, and m (1≤A,B≤109). Each of the next n lines has one of a1,…,an, and each of the m lines after that has one of b1,…,bm.
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).