USACO Gold 2016 January - Radio Contact

Authors: Neo Wang, Melody Yu

Official Analysis

Video Solution

Note: The video solution might not be the same as other solutions. Code in C++.

Explanation

The key dp\texttt{dp} observation to make here is already stated in the problem statement: "Farmer John can either stay put at his current location, or take one step forward", and likewise for Bessie. Thus, when constructing our dp\texttt{dp}, we can set dp[i][j]\texttt{dp}[i][j] equal to the best distance at Farmer John's move ii and Bessie's move jj.

Notice that it is hard to calculate a cumulative distance if we leave the string unprocessed (meaning that we read from the string directly). To resolve this, we can simply calculate the coordinates (i,j)(i,j) at every step of Bessie and Farmer John's path. In our implementation, we map each character to their appropriate dx, dy arrays in order to apply the appropriate changes, storing Farmer John's position at move ii as jl[i]\texttt{jl}[i] and Bessie's position at move jj at bl[j]\texttt{bl}[j].

After this is done, we start building our dp\texttt{dp}:

Either one of the following happens:

  1. Farmer John takes a step (i+1)(i+1): dp[i+1][j]=min(dp[i+1][j],dp[i][j]+dist(jl[i+1],bl[j]))\texttt{dp}[i+1][j] = \min(\texttt{dp}[i+1][j], \texttt{dp}[i][j] + \text{dist}(\texttt{jl}[i+1], \texttt{bl}[j]))

  2. Bessie takes a step (j+1)(j+1): dp[i][j+1]=min(dp[i][j+1],dp[i][j]+dist(jl[i],bl[j+1]))\texttt{dp}[i][j+1] = \min(\texttt{dp}[i][j+1], \texttt{dp}[i][j] + \text{dist}(\texttt{jl}[i], \texttt{bl}[j+1]))

  3. Both Farmer John and Bessie take steps (i+1)(i+1) and (j+1)(j+1): dp[i+1][j+1]=min(dp[i+1][j+1],dp[i][j]+dist(jl[i+1],bl[j+1]))\texttt{dp}[i+1][j+1] = \min(\texttt{dp}[i+1][j+1], \texttt{dp}[i][j] + \text{dist}(\texttt{jl}[i+1], \texttt{bl}[j+1]))

Implementation

Time Complexity: O(NM)\mathcal{O}(NM)

C++

Code Snippet: C++ Short Template (Click to expand)
int N, M;
const int INF = 1e9 + 7;
const int MX = 1e3 + 1;
int sq(int a) { return a * a; }
int dist(pi a, pi b) { // distance squared between two points

Java

import java.io.*;
import java.util.*;
public class radio {
public static int[][] fjLocs;
public static int[][] bLocs;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new FileReader("radio.in"));
PrintWriter pw = new PrintWriter(new FileWriter("radio.out"));

Join the USACO Forum!

Stuck on a problem, or don't understand a module? Join the USACO Forum and get help from other competitive programmers!