USACO Gold 2022 Open - Apple Catching

Author: Qi Wang

Table of Contents

ExplanationImplementation

Official Analysis (Java)

Explanation

In order for a cow to catch an apple, it must arrive before the apple hits the number line. Let item ii represent the cow and item jj represent the apple. Therefore, to catch the apple, xixjtjti|x_i - x_j| \le t_j - t_i must be satisfied. After extracting the absolute value, we get these two inequalities.

xjtjxitix_j - t_j \le x_i - t_i
xi+tixj+tjx_i + t_i \le x_j + t_j

We represent each item as a point (xiti,xi+ti)(x_i - t_i, x_i + t_i). According to the inequalities above, in order for a cow to catch an apple, the point of the apple must be to its top-left. Thus we can sort in ascending order based off xitix_i - t_i and greedily assign apples with larger xi+tix_i + t_i values to each cow. To maximize the number caught, we must pair each cow with the lowest y-coordinate apples that still meet above conditions.

Implementation

Time Complexity: O(NlogN)\mathcal{O}(N \log N)

C++

#include <bits/stdc++.h>
using namespace std;
const int MAX_N = 2e5;
struct Item {
int q; // type (cow or apple)
int t; // time of entry
int x; // position
int n; // amount

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!