USACO Silver 2019 December - Milk Visits

Authors: Qi Wang, Tanish Tyagi

Problem Statement

Official Analysis

Time Complexity: O(N+M)\mathcal{O}(N + M)

We can use a DFS to create connected components from an adjacency list (which is made when we process the roads between the farms). Each connected component will contain farms that all have the same breed.

Adjacency List based off sample test case:

12,51\rightarrow 2,5

21,3,42\rightarrow 1,3,4

323\rightarrow 2

424\rightarrow 2

515\rightarrow 1

There are three connected components of the same cow breed in this graph:

  • Component 11: Farms 11, 22, and 44
  • Component 22: Farm 33
  • Component 33: Farm 55

Create an array comp\texttt{comp} such that comp[A]\texttt{comp}[A] is the component of farm AA.

comp=[1,1,2,1,3]\texttt{comp} = [1, 1, 2, 1, 3] (1-indexed)

We evaluate 3 conditions to check whether the farmer will be happy:

  1. Farms AA and BB are part of the same component. This means the path between AA and BB only contains cows of the same breed. If the farmer prefers milk from this breed, then we should output 11.
  2. Farms AA and BB are part of different components. This means that the farmer will always be satisfied because the path between AA and BB contains both breeds of cows. We should output 11.
  3. If cases 11 and 22 are not met, then we should output 0.

Queries for Sample Test Case:

  1. Farms 11 and 44 are in the same component, and since Farmer 11's preferred cow is Holstein, they will be satisfied. (11)
  2. Farms 11 and 44 are in the same component, but since Farmer 22's preferred cow is Guernsey, they will be unsatisfied. (00)
  3. Farms 11 and 33 are in different components, so Farmer 33 will be satisfied. (11)
  4. Same logic as query 33. (11)
  5. Farm 55 is Guernsey, and Farmer 55's preferred cow is Holstein, they will be unsatisfied. (00)

C++

//Official Solution modified by Qi Wang
#include <bits/stdc++.h>
using namespace std;
typedef vector<int> vi;
#define FOR(i,a,b) for (int i = (a); i < (b); ++i)
#define F0R(i,a) FOR(i,0,a)
#define ROF(i,a,b) for (int i = (b)-1; i >= (a); --i)

Java

//Created by Qi Wang
import java.util.*;
import java.io.*;
public class milkvisit {
static int N, M, num=1;
static boolean[] col;
static int[] comp;
static List<Integer>[] adj;

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!