Fenced In (Gold)
Time limit2sMemory limit512 MB
Remove fence segments of minimum total length so every region of the fenced grid connects to every other.
- Level
Medium7 of 10
- Topics
- Minimum spanning tree, Greedy, Sorting
- Solved
- No attempts yet
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 and . Farmer John built vertical fences () at distinct positions (), and the fence at runs from to . He also built horizontal fences () at distinct positions (), and the fence at runs from to . Every vertical fence crosses every horizontal fence, so the field is cut into 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 , , , and (). Each of the next lines has one of , and each of the lines after that has one of .
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).