USACO Gold 2018 January - Cow At Large
Authors: Qi Wang, Jesse Choe, George Pong
Suppose that a given farmer reaches Bessie at barn ; this is only possible if that farmer reached barn 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 at the same time or earlier than Bessie if . Here, represents the shortest distance between any given farmer and the -th barn, and represents the shortest distance between Bessie and the -th barn. Note that can also be represented as the tree depth at barn with the tree rooted at barn .
We can run BFS to find and DFS or BFS to find . Once we find these shortest distances, we can simulate Bessies' movement by "catching" her when . 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:
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 dequewith 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!