Surround the Islands with Fence
Time limit1sMemory limit128 MB
Given N edges that form disjoint polygon islands and a symmetric vertex-to-vertex boat cost matrix, find the minimum total cost of round trips needed to fence every island, starting anywhere.
- Level
Hard8 of 10
- Topics
- Graph, Minimum spanning tree, Union-find, Implementation
- Solved
- No attempts yet
Problem
Farmer John has bought a large farm made up of several islands and wants to raise dairy cows there. He wants to surround every island with fence.
Each island is shaped like a polygon. John fences one island at a time, moving clockwise around it and building fence one side at a time between consecutive vertices. Walking around the border of an island costs nothing.
To fence every island he must travel by boat to the others. John may start fencing at any vertex, and from any vertex he passes he may take a boat to some vertex on another island, fence all the way around that island, and then IMMEDIATELY return to the very same vertex of the original island along the same path he came. Thus each boat trip is a round trip and costs twice the one-way fare.
The cost of boating between each pair of vertices is given by a symmetric cost matrix.
The islands are given as vertex pairs ; you must work out how to assemble these edges into islands. Vertices are numbered through , and each vertex belongs to exactly one island.
Find the minimum cost of surrounding all the islands with fence.
Constraints: , , and every boat cost is between and inclusive.
Input
- Line 1: an integer .
- Lines 2 through : each line gives two space-separated vertices and forming one side of an island's border.
- Lines through : the rows of the cost matrix. Line contains integers giving the boat cost from vertex to every other vertex. The matrix is symmetric.
Output
- Print a single integer: the minimum cost of building the fence around all islands.
Hint
The figure below shows three islands.
1 10 4
xxxxxxx x
xxxxxxxxx xxxx
7 xxxxxxxxxxx 6 xxxxxxx
xxxxxxxxxxx 11 xxxxxxxxxx 5
xxxxxxx
xxx
3 12 xxxxxxx 2
xxxxxxxx
xxxxxxxx
xxxxxxxxx
xxxxxxxxx
xxxxxxxxxx
xxxxxxxxxx
8 xxxxxxxxxx 9
The three islands consist of vertices , , and .
For instance, boating from vertex to vertex , fencing the second island, and returning to costs ; boating from to , fencing the third island, and returning costs . The first island needs no boat trip because it is the starting island, so the total is . More than one optimal route exists.