The basic property of modulus is
1. |x| = x if x>=0
2. |x| = -x if x<0
Using this, the equation y = |x-a|+b
can be written as
1. y = x + (b-a) if x >= a
2. y = (b+a) - x if x<a
Since b
and a
are constants, we can use pre-computation to get answers per query in constant time.
For a given x
, there are two cases:
- The minima lies to the left of
x
(i.e. a < x
). If we know the minimum value of b-a
for all lines with a < x
, we can get the answer in O(1) time.
- Similarly, when the minima lies on the right of
x
(i.e. a >= x
), if we know the minimum value of b+a
for all lines with a >= x
, we can get the answer in O(1) time.
To summarise, we need to know the minimum value of b-a
for all a
on the left of x
and the minimum value of b+a
for all a
on the right of x
. This can easily be done using a simple prefix and/or suffix array implementation.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…