template <typename F> int find_min(int l, int r, const F &f) {
    while (r - l > 3) {
        int m1 = l + ((r - l) / 3);
        int m2 = r - ((r - l) / 3);
        f(m1) > f(m2) ? l = m1 : r = m2;
    }
 
    int res = l;
    for (int i = l + 1; i <= r; i++) {
        if (f(i) < f(res)) res = i;
    }
    return res;
}

haybale distribution

  • compute prefix sums for , define
  • total wasted is
  • where is the index of , thus the count of
    • left side is
    • right side is
    • , and is
  • find inflection point of using a search, minimum is solution
  • (technically there is duplicate handling but not in scope)