Explanation
Observation
We can think of the output slots as positions on the number line. Consider a wagon that starts moving at time . Then, that wagon can catch a candy if its position at time is within the range . Let's define this range as the range of acceptable wagon positions for at time . With every passing second, this range is reduced by unit to the left and to the right of . Generally, the range of acceptable wagon positions for at time (where ) is:
At time this range has been shrunk to a single point, .
A wagon can catch a candy before , if the range of acceptable wagon positions for at time includes , (since the wagon will be at to catch ). However, at time the range for acceptable wagon positions of will have been reduced to
But needs to be inside this range, therefore:
This is equivalent to saying that the range of acceptable wagon positions of is fully contained within the range of .
We have therefore concluded that two candies can be caught by the same wagon if (and only if) their ranges of acceptable wagon positions are nested.
Finding the minimum number of wagons
We can think of each candy as its range of acceptable wagon positions at time 0 (note that each candy corresponds to a unique range and vice versa). We can conclude that a wagon can catch a sequence of candies , if they form a sequence of nested ranges. It follows that the minimum number of wagons needed is the longest sequence of non-nested ranges.
Two ranges , that are not nested adhere to: .
If we sort the candies by the left endpoint of their ranges such that
then a sequence of non-nested ranges would correspond to an increasing sequence of right endpoints. Therefore, the minimum number of required wagons would correspond to the length of the longest increasing sequence of right endpoints.
Assigning the candies to wagons
By following the binary search algorithm described in the LIS module, we can assign the candies with the same LIS length to the same wagon. The ranges that have the same LIS length cannot be nested. If they were, we could use the inside range to increase the LIS of the outside one by 1.
Implementation
Time Complexity:
Warning!
Watch out for the case , in which case we must sort by decreasing right endpoint to ensure they would not be counted as non-nested ranges.
C++
#include <bits/stdc++.h>using namespace std;typedef pair<int, int> pi;int main() {int n;cin >> n;vector<pi> candies(n);
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!