cses - Houses and Schools

Author: Dustin Miao

Table of Contents

ExplanationImplementation

Explanation

The final answer will be of the form k1c1+k2c2++kncnk_1 c_1 + k_2 c_2 + \dots + k_n c_n. The sequence kk 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 11 or decreasing by 11. Define the DP states as follows:

  • fi,mf_{i,m} - minimum distance considering the first ii elements using mm schools ending at a valley
  • gi,mg_{i,m} - minimum distance considering the first ii elements using mm schools ending at a mountain

The transitions are the following:

gi,m=minji{fj,m+k=j+1ick(kj)}g_{i,m} = \min_{j \leq i} \left \{ f_{j,m} + \sum_{k = j + 1}^i c_k \cdot (k - j) \right \}
fi,m=minj<i{gj,m1+k=j+1ick(ik)}f_{i,m} = \min_{j < i} \left \{ g_{j,m-1} + \sum_{k = j + 1}^i c_k \cdot (i - k) \right \}

The transitions take linear time, but can be optimized to amortized constant time using convex hull trick.

Define the following:

  • tk=i=1kcit_k = \sum_{i = 1}^k c_i
  • pk=i=1kciip_k = \sum_{i = 1}^k c_i \cdot i
  • sk=i=1kci(ni+1)s_k = \sum_{i = 1}^k c_i \cdot (n - i + 1)

These can be precomputed in O(n)\mathcal{O}(n) time.

The DP equations becomes:

gi,m=minji{fj,m+pipjj(titj)}g_{i,m} = \min_{j \leq i} \left \{ f_{j,m} + p_i - p_j - j \cdot (t_i - t_j) \right \}
fi,m=minj<i{gj,m1+sisj(ni)(titj)}f_{i,m} = \min_{j < i} \left \{ g_{j,m-1} + s_i - s_j - (n - i)(t_i - t_j) \right \}

With a bit of rearranging:

gi,m=minji{(fj,mpj+jtj)jti}+pig_{i,m} = \min_{j \leq i} \left \{ (f_{j,m} - p_j + jt_j) - jt_i \right \} + p_i
fi,m=minj<i{(gj,m1sj)+tj(ni)}+siti(ni)f_{i,m} = \min_{j < i} \left \{ (g_{j,m-1} - s_j) + t_j(n - i) \right \} + s_i - t_i(n - i)

Because both the slopes and the query points are monotonic, this can be maintained using a deque in amortized O(1)\mathcal{O}(1). The total complexity is O(nm)\mathcal{O}(nm).

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!