Hi, in a past contest I meet this problem: http://coj.uci.cu/24h/problem.xhtml?abb=2067 I couldn't solve it and affter I study some algorithms, I saw again and I tryed to solve it but I couldn't do it again. I think I need to use Line Sweep to solve it but I wonder if anybody knows an easier way (I don't know too mucho about line sweep). Thanks and sorry for my english.
For a given point (x1, y1), it is necessary to find the closest point to it (x2, y2). The are four cases:
x2 >= x1 and y2 >= y1
x2 >= x1 and y2 <= y1
x2 <= x1 and y2 >= y1
x2 <= x1 ans y2 <= y1
Let's see how to solve the case #1.
Since x2 >= x1 and y2 >= y1, then dist(p1, p2) = |x2 — x1| + |y2 — y1| = x2 — x1 + y2 — y1 = (x2 + y2) — (x1 + y1).
As you can see, the best option in this case is to choose the point such that x2 + y2 is minimum. This can be solved using a data structure supporting the following two functions:
query(Y)
: finds the point (x, y) such that y >= Y and x + y is minimum among all the points in the structure.add((x, y))
: adds the point (x, y) to the structure.An example of such data structure is a Binary Indexed Tree.
Let p be the input points:
The other three cases can be solved in a similar way.
What you mean it's a 'Quad Tree', I implement it but it gives me TLE (I using java), a friend of me solved it using 2D-Tree with 'Quick Select' algorithm for building the tree.