cses - Houses and Schools
Author: Dustin Miao
Explanation
The final answer will be of the form . The sequence is a series of "mountains" and "valleys", the valleys occuring at the indicies of the schools and the mountains occuring at the midpoints between two schools. By partitioning this sequence along these points, we get a series of sequences that are increasing by or decreasing by . Define the DP states as follows:
- - minimum distance considering the first elements using schools ending at a valley
- - minimum distance considering the first elements using schools ending at a mountain
The transitions are the following:
The transitions take linear time, but can be optimized to amortized constant time using convex hull trick.
Define the following:
These can be precomputed in time.
The DP equations becomes:
With a bit of rearranging:
Because both the slopes and the query points are monotonic, this can be maintained using a deque in amortized . The total complexity is .
Implementation
C++
#include <bits/stdc++.h>using namespace std;namespace geo {const double EPS = 1e-9;template <typename T> class point {static_assert(is_arithmetic<T>::value, "T must be an arithmetic type");public:
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!