USACO Gold 2018 January - Cow At Large

Authors: Qi Wang, Jesse Choe, George Pong


Official Analysis

Suppose that a given farmer reaches Bessie at barn ii; this is only possible if that farmer reached barn ii either:

  • At the same time as Bessie
  • At an earlier time than Bessie

This means that we can treat this problem as a shortest path problem, where the farmer reaches barn ii at the same time or earlier than Bessie if dist1[i]dist2[i]\texttt{dist1[i]} \leq \texttt{dist2[i]}. Here, dist1[i]\texttt{dist1[i]} represents the shortest distance between any given farmer and the ii-th barn, and dist2[i]\texttt{dist2[i]} represents the shortest distance between Bessie and the ii-th barn. Note that dist2[i]\texttt{dist2[i]} can also be represented as the tree depth at barn ii with the tree rooted at barn kk.

We can run BFS to find dist1[i]\texttt{dist1[i]} and DFS or BFS to find dist2[i]\texttt{dist2[i]}. Once we find these shortest distances, we can simulate Bessies' movement by "catching" her when dist1[i]dist2[i]\texttt{dist1[i]} \leq \texttt{dist2[i]}. Once Bessie is caught, we can stop her movement and increase the total number of farmers by 1. This greedily finds the minimum number of farmers, since we only store the "optimal" farmers in our answer.

Implementation

Time Complexity: O(V+E)\mathcal{O}(V+E)

C++

#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using vl = vector<ll>;
using pl = pair<ll, ll>;
#define pb push_back
#define f first
#define s second

Python

from collections import deque
with open("atlarge.in", "r") as infile:
n, k = map(int, infile.readline().split())
graph = [[] for _ in range(n)]
for _ in range(n - 1):
f, t = map(lambda i: int(i) - 1, infile.readline().split())
graph[f].append(t)
graph[t].append(f)

Java

import java.io.*;
import java.util.*;
public class AtLarge {
static int N, K, A = 0;
static List<Integer>[] adj;
static int[] depth, leaf, inDeg, parent;
public static void main(String[] args) throws Exception {
Kattio io = new Kattio("atlarge");

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!