Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
175 views
in Technique[技术] by (71.8m points)

algorithm - Query min value at x of many equations in the form |x-a| + b

Kind of unrelated to what I was doing, but I stumbled on this interesting data structure. I can't figure out a few details.

Suppose I have like N<10^5 equations in the form y = |x-a| + b, with 0 < x, a, b < 10^5. After O(N) preprocessing, for any x, I want to find the minimum value out of all these equations in constant time.

Here's what I have so far: add the functions one by one in increasing values of a, somehow find the intersection between the new function and the min existing function, then store intersections. The intersections can tell us what equation to use for the min. Then we can use binary search for log time queries, but since x<10^5, we can just go through all values and precompute the correct min value for each x

Visualization, where the black is the min values

enter image description here

question from:https://stackoverflow.com/questions/65855935/query-min-value-at-x-of-many-equations-in-the-form-x-a-b

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:

  1. 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.
  2. 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...