USACO Training: Cow Tours (and Floyd-Warshall's)
USACO Training: Cow Tours
Idea:
Let us first initially use Floyd-Warshall's to calculate the all-pairs shortest paths.Afterwords, our first instinct would be to do the following:
- Select a node i,
- Select a node j,
- Create an edge between i and j,
- Do FW again,
- Loop through array to find the maximum edge.
How can we optimize this?
Let us introduce a new measure, the longest possible (non-infinite) distance between a node X and any other node. Let it be stored in an array called "far". We notice that since we have already done Floyd-Warshalls on the grid, we can precalculate this array. Notice that now, we instantly reduce the time by a factor of O(n^4) - we can instantly, i.e. in O(1), calculate the diameter if we added an edge between I and J!
However, we would need to calculate the diameters first.
How?
The diameter of a node X is the collective maximum of far[i] as long as dist[X][i] is not infinity.
The diameter if we collect node I and node J is the maximum of the following;
- diameter of I,
- diameter of J,
- far[i] + far[j] + EuclideanDistance(i, j)
Bug List
1. I hard-coded a permanent 2 fields into my program. However, it isn't important - all we need are to connect any two fields.2. Floyd-Warshalls:
Floyd-Warshall Loop Order
K, I, J
Explanation -If it were I, J, K, if K acted as an intermediate point, the path I -> J would only get one intermediate point.
However, if we looped over K as a set of intermediate points, then I -> J would get all the intermediate points that it needed.
If the loop order is I, J, K, we would keep K as the intermediate point. However, choosing the maximum would ALWAYS result in only 1 intermediate point being used.
Comments
Post a Comment