Originally, the closest point in the two-dimensional plane had an O (nlogn) algorithm, but the partitioning algorithm was not practical.
Shield has come up with a very elegant algorithm:
Rotate the system randomly, sort by X, and then perform bare search + break.
Normally, the raw search by X will be stuck by some data cards (some boring people should not say something like y)
But why is it stuck? It's nothing more than the break won't work if it's all in the first row!
The random rotation mechanism is not easy to get stuck with any data!
Therefore, the algorithm has O (fast rank + K * n) Complexity. In actual tests, the algorithm has a very good performance. Find the closest point in the Three-dimensional space, N = 1000000 can be obtained within five seconds (because of the existence of real number operations, the constant is increased)
In addition, the scalability of the algorithm is very good, and it can be done in any dimension space, and the programming complexity is extremely low (almost a fast line is enough)
In actual implementation, you don't have to actually rotate the coordinate system. Just random a vector and sort it by the projection length of all points on the vector (using dot product) as the keyword.
Code attachment (calculate the closest point in a 3D space, and the distance is defined as a Euclidean distance without an EIP ):
Program syj; <br/> const E = 1e-8; maxn = 1000005; <br/> var N, I, j: longint; K: real; XX, YY, ZZ, ANS, TMP: int64; <br/> B: array [1 .. maxn] of longint; <br/> A, x, y, z: array [1 .. maxn] of int64; <br/> C: array [1 .. maxn] of real; <br/> procedure sort (L, R: longint); <br/> var I, j: longint; k, Z: int64; <br/> begin <br/> I: = L; J: = r; K: = A [(L + r)> 1]; <br/> repeat <br/> while K-A [I]> E do Inc (I ); <br/> while a [J]-k> E do Dec (j); <br/> If I <= J then begin <br/> Z: = A [I]; A [I]: = A [J]; A [J]: = z; <br/> Z: = B [I]; B [I]: = B [J]; B [J]: = z; <br/> Inc (I); Dec (j); <br/> end; <br/> until I> J; <br/> if l <j then sort (L, J); <br/> If I <r then sort (I, r); <br/> end; <br/> begin <br/> randomize; <br/> assign (input, 'closest. in '); reset (input); <br/> assign (output, 'closest. out'); rewrite (output); <br/> readln (n); <br/> XX: = random (1000) + 1; YY: = random (1000) + 1; ZZ: = random (1000) + 1; <br/> K: = 1/(XX * xx + YY * YY + ZZ * zz ); <br/> for I: = 1 to n do begin <br/> Read (X [I], Y [I], Z [I]); <br/> A [I]: = x [I] * xx + Y [I] * YY + Z [I] * ZZ; <br/> B [I]: = I; <br/> end; <br/> sort (1, N); <br/> ans: = 999999999999999999; <br/> for I: = 1 to n do begin <br/> for J: = I + 1 to n do begin <br/> TMP: = sqr (X [B [I]-X [B [J]) + sqr (Y [B [I]-y [B [J]) + sqr (Z [B [I]-Z [B [J]); <br/> If TMP <ans then ans: = TMP; <br/> if K * sqr (A [J]-A [I])-ans>-E then break; <br/> end; <br/> writeln (ANS); <br/> close (input); close (output); <br/> end.