USACO Gold 2017 February - Why Did the Cow Cross The Road II

Authors: Brad Ma, Jesse Choe

Table of Contents

ExplanationImplementation

Official Analysis (C++)

Explanation

Let's define dp[i][j]\texttt{dp}[i][j] as the maximum number of disjoint friendly crosswalks up to field ii on the first side of the road and field jj on the second side of the road. We can build a crosswalk between fields ii and jj as long as there isn't a crosswalk between fields ii, j1j - 1 and i1i - 1, jj. Thus, dp[i][j]=max(dp[i1][j],dp[i][j1],dp[i1][j1]+(id[i]id[j]4))\texttt{dp}[i][j] = \max(\texttt{dp}[i - 1][j], \texttt{dp}[i][j - 1], \texttt{dp}[i - 1][j - 1] + (|\texttt{id}[i] - \texttt{id}[j]| \leq 4)), where id[i]\texttt{id}[i] and id[j]\texttt{id}[j] represent the breed IDs of the cows in the ii-th and jj-th fields, respectively.

The answer is dp[N][N]\texttt{dp}[N][N].

Implementation

Time Complexity: O(N2)\mathcal{O}(N ^ 2)

C++

#include <bits/stdc++.h>
using namespace std;
const int MAXN = 1000;
int dp[MAXN + 1][MAXN + 1];
int main() {
freopen("nocross.in", "r", stdin);
freopen("nocross.out", "w", stdout);

Java

import java.io.*;
import java.util.*;
public class NoCross {
static int[] firstSide;
static int[] secondSide;
static int[][] memoization;
static boolean friendly(int cow1, int cow2) {
if (Math.abs(firstSide[cow1] - secondSide[cow2]) <= 4) { return true; }

Python

with open("nocross.in") as read:
n = int(read.readline().strip())
"""
id1 represents the breed ID of the fields
on the first side of the road
id2 represents the breed ID of the fields
on the other side of the road.
"""
id1 = [0]

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!