33 if (size <= 0 || max_step < min_step || min_step >= size) {
38 tprintf(
"min = %d, max=%d\n", min_step, max_step);
41 for (
int i = 0;
i < size; ++
i) {
42 for (
int offset = min_step; offset <= max_step; ++offset) {
43 DPPoint *prev = offset <=
i ? points +
i - offset :
nullptr;
44 int64_t new_cost = (points[
i].*cost_func)(prev);
45 if (points[
i].best_prev_ !=
nullptr && offset > min_step * 2 &&
46 new_cost > points[
i].total_cost_) {
50 points[
i].total_cost_ += points[
i].local_cost_;
52 tprintf(
"At point %d, local cost=%d, total_cost=%d, steps=%d\n",
i, points[
i].local_cost_,
53 points[
i].total_cost_, points[
i].total_steps_);
57 int best_cost = points[size - 1].total_cost_;
58 int best_end = size - 1;
59 for (
int end = best_end - 1; end >= size - min_step; --end) {
60 int cost = points[end].total_cost_;
61 if (cost < best_cost) {
66 return points + best_end;
71 if (prev ==
nullptr || prev ==
this) {
72 UpdateIfBetter(0, 1,
nullptr, 0, 0, 0);
76 int delta =
this - prev;
77 int32_t n = prev->n_ + 1;
78 int32_t sig_x = prev->sig_x_ + delta;
79 int64_t sig_xsq = prev->sig_xsq_ +
static_cast<int64_t
>(delta) * delta;
80 int64_t cost = (sig_xsq - sig_x * sig_x / n) / n;
81 cost += prev->total_cost_;
82 UpdateIfBetter(cost, prev->total_steps_ + 1, prev, n, sig_x, sig_xsq);
87void DPPoint::UpdateIfBetter(int64_t cost, int32_t steps,
const DPPoint *prev, int32_t n,
88 int32_t sig_x, int64_t sig_xsq) {
89 if (cost < total_cost_) {
void tprintf(const char *format,...)
int64_t(DPPoint::*)(const DPPoint *) CostFunc
static DPPoint * Solve(int min_step, int max_step, bool debug, CostFunc cost_func, int size, DPPoint *points)
int64_t CostWithVariance(const DPPoint *prev)