1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94
| #include<stdio.h> #include<stdlib.h> #include<math.h> #include <sys/time.h>
#define INF 99999 #define N 10000
int m,t; int temp[N];
struct node { double x; double y; }point[N];
int compar(const void* a, const void* b) { struct node A = *(struct node*)a; struct node B = *(struct node*)b; if (A.x != B.x) return A.x - B.x; else return A.y - B.y; }
double Min_distance(double left, double right) { return left < right ? left : right; }
double distance(int left, int right) { return sqrt((point[left].x - point[right].x) * (point[left].x - point[right].x) + ((point[left].y - point[right].y) * (point[left].y - point[right].y))); }
double Closest_Pair(int left, int right) { double End_dis = INF; int i = 0, j = 0, k = 0;
if (left == right) return End_dis;
if (right - left == 1) return distance(left, right);
int mid = (left + right) / 2;
double distance_left = Closest_Pair(left, mid); double distancer_ight = Closest_Pair(mid + 1, right);
End_dis = Min_distance(distance_left, distancer_ight);
for (i = left; i <= right; i++) { if (fabs(point[mid].x - point[i].x) <= End_dis) temp[k++] = i; } for (i = 0; i <= k - 1; i++) for (j = i + 1; j <= k - 1 && j < i + 7; j++) if (fabs(point[temp[j]].y - point[temp[i]].y) < End_dis) { if(End_dis>=distance(temp[i], temp[j])) { m=temp[i]; t=temp[j]; } else m = left,t = right; End_dis = Min_distance(End_dis, distance(temp[i], temp[j])); } return End_dis; }
int main() { struct timeval start, end; int n; scanf("%d",&n); double a; for (int i = 0; i < n; i++) scanf("%lf %lf", &point[i].x, &point[i].y); gettimeofday(&start, NULL); qsort(point, n, sizeof(point[0]), compar); a = Closest_Pair(0, n - 1); gettimeofday(&end, NULL); printf("the shortest distance is:%.10lf\n", a); printf("the co-ordinates of the pair of points is:\n%.10lf %.10lf\n",point[m].x,point[m].y); printf("%.10lf %.10lf\n",point[t].x,point[t].y); long elapsed = (end.tv_sec - start.tv_sec)*1000000.0 + end.tv_usec - start.tv_usec; printf("%.ld ms elapsed\n", elapsed); return 0; }
|