Efficient function summation calculation algorithm

We are given N points of the form (x, y) , and we need to calculate the following function:

F (i, j) = (| X [i] - X [j] |) * (| Y [i] - Y [j] |)

Calculate the summation F (i, j) for all ordered pairs (i, j)

N <= 300000

I am looking for a solution O(N log N).

My initial thought was to sort the points by X and then use BIT, but I cannot formulate a clear solution.

+4
source share
1 answer

I have a solution using O(N log(M))time and O(M)memory, where Mis the size of the range Y. This is similar to what you are thinking.

, X .

A (X[i] - X[j]) * (Y[i] - Y[j]) i > j , Y[i] > Y[j] B i > j , Y[i] < Y[j].

A + B O(N) , A - B. , A.

, [a, b) b = a + 2^k k. ( , , , ?) node inteval [Y_min, Y_max] Y.

node [a, b) i f(a, b, i) :

f(a, b, i)(X, Y) = sum of (X - X[j]) * (Y - Y[j]) for all j such that j < i and Y[j] < Y

P * XY + Q * X + R * Y + S, P, Q, R, S.

, i = 0, f(a, b, i)(X[i], Y[i]). i i + 1, intevals [a, b), Y[i]. i = N, A.

O(M), .

+1

Source: https://habr.com/ru/post/1598862/


All Articles