This question is: In a Cartesian coordinate system, n points (points cannot exceed 100,000 !) The distribution is different. In the n points, find the distance between the two points with the shortest distance!
Idea: The idea of this question is very simple, that is, enumeration and comparison, right? Then we naturally want to use the brute force method to solve the problem, but because there are a maximum of 0.1 million points and the time complexity is o (n * n), the result is naturally time-out!
This topic is divided into two parts by many Daniel. I didn't use it here. I read the advanced problem-solving report of the experts online and found something! --It is to sort the x and y coordinates of n points and then compare them! -- In this way, it takes much less time to compare!
The code is as follows:
# Include <cstdio> # include <iostream> # include <cstring> # include <cmath> # include <algorithm> using namespace std; const double inf = 5201314; struct Point // defines the struct of a vertex! {Double x, y;} point [201314]; double ans = inf; int cmp (Point a, Point B) {// sorting condition! By default, x is sorted from small to large! Otherwise, sort by y from small to large! If (. x = B. x) return. y <B. y; return. x <B. x;} double getdis (Point a, Point B) {double ki =. x-b.x; double ll =. y-b.y; return sqrt (ki * ki + ll * ll); // calculate the distance between two points !} Double now_min (int begin, int num) {double min = inf; for (int I = begin + 1; I <num; I ++) {double dis = getdis (point [begin], point [I]); if (min> dis) min = dis; else break; // because I have already sorted the order, // therefore, the distance between vertex I and the point next to it is getting bigger and bigger, so else can exit directly! } Return min;} int main () {int num; // it indicates the number of point de mu! While (scanf ("% d", & num )! = EOF) {if (! Num) break; for (int I = 0; I <num; I ++) scanf ("% lf", & point [I]. x, & point [I]. y); sort (point, point + num, cmp); // sort by x value from small to large! Ans = inf; for (int I = 0; I <num-1; I ++) ans = ans <now_min (I, num )? Ans: now_min (I, num); // A simple comparison! Printf ("%. 2lf \ n", ans/2);} return 0 ;}
Hdu-1007