Explanation
Let's first think about how to determine if a cow can go from at time to at time .
The shortest path a cow can take is the straight line connecting to , which has a length of
by the distance formula.
Now, the cow's journey is possible if and only if this length is no greater than . In other words, we have the following inequality:
Therefore, we can check if the inequality holds for each cow and grazing site, and if every grazing site satisfies the inequality for a particular cow, then it is a suspect. Otherwise, it must be innocent.
Now, rather than using brute force to iterate through all cows and grazing sites, we use the condition that a cow can reach any grazing site from another within the specified times.
Consider a cow at at time and two grazing sites at and at times and , where . If the cow can reach the grazing site at , then it can also reach the grazing site at . The same is true when .
This means that for each cow, we only need to check the two grazing sites with times closest to their reported time! We can find these two sites by sorting the list of grazing sites by time and using binary search, which is fast enough to solve the problem.
Implementation
Time Complexity:
C++
#include <bits/stdc++.h>using namespace std;struct Event {int t, x, y;bool operator<(const Event &other) const { return t < other.t; }};Event read() {
Java
import java.io.*;import java.util.*;public class CowLibi {private static class Event implements Comparable<Event> {int t, x, y;private Event(int t, int x, int y) {this.t = t;this.x = x;
Python
import bisectfrom typing import Tupleg, n = map(int, input().split())def read():x, y, t = map(int, input().split())return t, x, y
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!