Table of Contents

ExplanationImplementation

Official Analysis (C++)

Explanation

Notice that at any point, if there is a cow adjacent to exactly three other cows, Farmer Nhoj must place a cow in the missing fourth spot. It now becomes a flood fill question, where, after adding each additional cow, we need to check how many more cows get added as a result, and add them to the answer.

We can maintain a 2D boolean array that represents whether each cell contains a cow and a queue that represents the coordinates of new cows being added.

At each step, we add the cow at (x,y)(x, y) to our queue. While the queue is not empty, we must pop the queue, and check if the current cow being added or any of its neighbors has exactly three adjacenct cows.

If any of the above cells has exactly adjacenct neighbors and has not already been visited, we push the coordinates of the missing fourth adjacenct cell into the queue.

At each step, count the total number of cells filled by keeping a counter. Then, the number of additional cows necessary would be the total number of cows minus the current number of cows.

It is also important to realize that the coordinates of additional cows may exceed the 1000 by 1000 grid set for new cows by up to 500 in each direction. So, you can make the grid 2000 by 2000.

Implementation

Time Complexity: O(N+G2)\mathcal{O}\left(N + G^2\right), where GG is the side length of the grid.

C++

#include <bits/stdc++.h>
using namespace std;
const int dx[4] = {1, 0, -1, 0};
const int dy[4] = {0, 1, 0, -1};
/** @returns the amount of neighbors that surrounds a specific cow in the grid */
int count_neighbors(vector<vector<bool>> &v, int x, int y) {
int count_neighbors = 0;
for (int i = 0; i < 4; i++) {

Java

import java.io.*;
import java.util.*;
public class ComfortableCows {
public static int[] dx = {1, 0, -1, 0};
public static int[] dy = {0, 1, 0, -1};
/** @returns the amount of neighbors that surrounds a specific cow in the grid */
public static int countNeighbors(boolean[][] v, int x, int y) {
int countNeighbors = 0;

Python

from collections import deque
from typing import List
dx = [1, 0, -1, 0]
dy = [0, 1, 0, -1]
def count_neighbors(v: List[List[bool]], x: int, y: int) -> int:
""":return: the amount of neighbors that surrounds a specific cow in the grid"""
count_neighbors = 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!