USACO Silver 2019 December - Milk Visits
Authors: Qi Wang, Tanish Tyagi, Kevin Sheng
Time Complexity:
We perform a search on the tree, identifying connected components of cows that all have the same breed.
In the sample test case, there are connected components:
- Component : Farms , , and
- Component : Farm
- Component : Farm
Next, we assign the farms in each component a number corresponding to the component they are in. For example, in the sample test case, farm would get the number , would get the number , and so on and so forth.
When checking if a visiting farmer going from farm to will be happy, there's two possible cases:
- 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 and otherwise.
- 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, and so we should always output .
Here's a walkthrough for the sample test case queries:
- 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++
#include <algorithm>#include <cassert>#include <fstream>#include <iostream>#include <vector>using std::cout;using std::endl;using std::vector;
Java
import java.io.*;import java.util.*;public class MilkVisits {public static void main(String[] args) throws IOException {BufferedReader read = new BufferedReader(new FileReader("milkvisits.in"));StringTokenizer initial = new StringTokenizer(read.readLine());int farmNum = Integer.parseInt(initial.nextToken());int queryNum = Integer.parseInt(initial.nextToken());
Python
with open("milkvisits.in") as read:farm_num, query_num = [int(i) for i in read.readline().split()]farms = read.readline()neighbors = [[] for _ in range(farm_num)]for f in range(farm_num - 1):f1, f2 = [int(i) - 1 for i in read.readline().split()]neighbors[f1].append(f2)neighbors[f2].append(f1)queries = []
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!