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:
  1. Select a node i,
  2. Select a node j,
  3. Create an edge between i and j,
  4. Do FW again,
  5. Loop through array to find the maximum edge.
However, the problem is soon obvious: this runs in O(n&5) time: o(n) for selecting i, o(n)for selecting j, o(n^3) for doing the FW, and O(n&3) for looping though the array.

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;
  1. diameter of I,
  2. diameter of J,
  3. 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

Popular posts from this blog

USACO Training "subset": Subset Sums

USACO 2018 Open: Talent Show

UVA 787 and Big Number Multiplication