Task about pairs of points and segments

105 Views Asked by At

Can you help me with problem? Given N <= 10^5 pairs of points, suppose they are written in array A, A[i][0] <= A[i][1]. Also, given M <= 10^5 pairs of segments, i-th pair given in form L_1[i], R_1[i], L_2[i], R_2[i]. For each pair of segments I need to find number of pairs from array A, such that for each pair (A[z][0], A[z][1]) it should be L_1[i] <= A[z][0] <= R_1[i] <= L_2[i] <= A[z][1] <= R_2[i]. I think here we can use scan line algorithm, but I don't know how to fit in time and memory. My idea works in N * M * log(N).

1

There are 1 best solutions below

2
On BEST ANSWER

If you map A[i] to a point (A[i][0], A[i][1]) on 2d-plane, then for each segment, basically you're just counting the number of points inside the rectangle whose left-bottom corner is (L_1[i], L_2[i]) and right-top corner is (R_1[i], R_2[i]). Counting the points on 2d-plane is a classic question which could be solved in O(n logn). Here are some possible implementations:

  • Notice that number of points in a rectangle P(l,b,r,t) could be interpreted as P(0,0,r,t)-P(0,0,l-1,t)-P(0,0,r,b-1)+P(0,0,l-1,b-1), so the problem can be simplified to calculating P(0,0,?,?). This could be done easily if we maintain a fenwick tree during the process which basically resembles scan line algorithm.

  • Build a persistent segment tree for each x-coordinate (in time O(n logn)) and calculate the answers for segments (in time O(m logn)).

  • Build a kd-tree and answer each query in O(sqrt(n)) time. This is not efficient but could be useful when you want to insert points and count points online.

Sorry for my poor English. Feel free to point out my typos and mistakes.