Table of Contents

ExplanationImplementation

Explanation

If we need to move from aa to bb with a slingshot from xx to yy that takes tt time, then it will take ax+by+t\left|a - x\right| + \left|b - y\right| + t time.

To eliminate the absolute values, we have to do a bit of casework. Note that the result for using a given slingshot is always in the form of t+(±a±x)+(±b±y)t + (\pm a \pm x) + (\pm b \pm y); because we are doing casework on the signs, we can separate the cost for using a slingshot from the values of aa and bb.

So, we can consider each of the four cases and use a range minimum segment tree to keep track of the best slingshots for each prefix/suffix of the array. My implementation processes the four cases in two iterations, where in one iteration axa \leq x, and in the other axa \geq x.

Implementation

Time Complexity: O((N+Q)logN)\mathcal{O}((N + Q) \log{N})

C++

#include <bits/stdc++.h>
using namespace std;
using ll = long long;
Code Snippet: Segment Tree (from the module) (Click to expand)
int main() {
freopen("slingshot.in", "r", stdin);
freopen("slingshot.out", "w", stdout);

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!