USACO Silver 2019 December - Milk Visits
Authors: Qi Wang, Tanish Tyagi
Appears In
Time Complexity:
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:
There are three connected components of the same cow breed in this graph:
- Component : Farms , , and
- Component : Farm
- Component : Farm
Create an array such that is the component of farm .
(1-indexed)
We evaluate 3 conditions to check whether the farmer will be happy:
- Farms and are part of the same component. This means the path between and only contains cows of the same breed. If the farmer prefers milk from this breed, then we should output .
- Farms and are part of different components. This means that the farmer will always be satisfied because the path between and contains both breeds of cows. We should output .
- If cases and are not met, then we should output 0.
Queries for Sample Test Case:
- Farms and are in the same component, and since Farmer 's preferred cow is Holstein, they will be satisfied. ()
- Farms and are in the same component, but since Farmer 's preferred cow is Guernsey, they will be unsatisfied. ()
- Farms and are in different components, so Farmer will be satisfied. ()
- Same logic as query . ()
- Farm is Guernsey, and Farmer 's preferred cow is Holstein, they will be unsatisfied. ()
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 Wangimport 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!