#P3141. [USACO16FEB] Fenced In P
[USACO16FEB] Fenced In P
Description
Farmer John has realized that his cows have recently developed a phobia of overly open spaces. To reduce their fear while grazing, FJ decides to build some horizontal and vertical fences in the pasture to divide it into smaller regions.
The entire pasture is a rectangle with corners at and . FJ builds vertical fences at distinct positions , each from to ; he builds horizontal fences at distinct positions , each from to . The vertical and horizontal fences intersect pairwise, dividing the entire pasture into regions.
Unfortunately, FJ forgot to add gates in the fences, so the cows are trapped in individual small regions. He can fix this by removing some fences. Each time, he can choose two adjacent regions and remove the fence that separates them. FJ’s goal is to allow the cows to reach any location in the pasture.
Here is an example:
+---+--+
| | |
+---+--+
| | |
| | |
+---+--+
After removing some fences:
+---+--+
| |
+---+ +
| |
| |
+---+--+
To minimize the work, FJ wants the total length of removed fences to be as small as possible.
Input Format
The first line contains four integers , with and .
The next lines each contain an integer , with .
The next lines each contain an integer , with .
Output Format
Output the minimum total length of fences to remove. The answer needs to 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
京公网安备 11011102002149号