Video Solution
Note: The video solution might not be the same as other solutions. Code in C++.
Explanation
Suppose we have a cow travelling horizontally at and another cow travelling vertically at . They will intersect at given that and . If a cow reaches this point first, then the later cow will be stopped.
However, cows can be stopped before reaching possible intersections with other cows. Thus, we need to sort our cows to process them in a way that avoids this issue. We sort our horizontal-bound cows by increasing vertical values, and we sort our vertical-bound cows by increasing horizontal values. The sorted order ensures that once we find a potential collision, all cows that could have been would have been stopped. We can then check each pair of cows based on the following criteria:
- If either cow has already been stopped, we can skip this pair.
- If their paths do not intersect, we can skip this pair.
- If neither has been stopped and they do intersect, we stop the cow that is further from the intersection.
Implementation
Time Complexity:
C++
#include <bits/stdc++.h>using namespace std;int main() {int n;cin >> n;vector<int> x_coordinates(n);vector<int> y_coordinates(n);vector<int> east_cows;
Java
import java.io.*;import java.util.*;public class StuckInARut {static int[] xCoordinates;static int[] yCoordinates;public static void main(String[] args) throws IOException {BufferedReader br = new BufferedReader(new InputStreamReader(System.in));int n = Integer.parseInt(br.readLine());
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!