USACO Gold 2016 January - Radio Contact

Author: Neo Wang

Problem Statement

Official Analysis

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++

#include <bits/stdc++.h> // see /general/running-code-locally
using namespace std;
using ll = long long;
using vi = vector<int>;
#define pb push_back
#define all(x) begin(x), end(x)
#define sz(x) (int)(x).size()

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!