Search code examples
algorithmoptimizationquery-optimizationcomputational-geometrykdtree

Faster Queries in plane


Problem I have to support Q queries of a set of n 2-D points in Cartesian plane lying in [0,M]x[0,M]. Points are given in advance.

Each query ask me to count the number of points enclosed in rectangle (x1,y1)*(x2,y2). (axis aligned rectangle).

constraints
0 < M < 10000

I want to know more about the algorithms used. Can we perform these queries more efficiently using this information that all the points and the queries are given in advance and the coordinates of points are bounded etc.

Variant: Instead of n points to begin with, Can we add n axis-aligned rectangular patches of points as n add operation in our data structure and then answer the same queries. [lazy segment trees kind of approach].


Solution

  • This is a classic 2d Binary Indexed Tree problem. Binary Indexed Tree can give you how many dots are in a rectangle from (0,0) to (x,y), now if you want to find out how many dots are in a rectangle indicated by (x1,y1) and (x2,y2), first you have to find the coordinates of the other two corner points of the rectangle. Let pUL, pUR, pBL, pBR be the four corner points of your rectangle representing upper left corner, upper right corner, bottom left corner and bottom right corner. By using inclusion-exclusion logic the number of dots enclosed in this rectangle is.

    q(p) // query on 2D-BIT for point p which gives how many dots are in 
         // rectangle represented by (0,0) and (p.x, p.y)
    result = q(pUR)-q(pUL)-q(pBR)+p(pBL)