最近点对模板:
-
1 #include
2 #include 3 #include 4 using namespace std; 5 const int MAXN = 100005; 6 struct POINT 7 { 8 double x, y; 9 int index; 10 void input() 11 { 12 scanf("%lf %lf", &x, &y); 13 } 14 }X[MAXN], Y[MAXN]; 15 bool cmpx(const POINT &a, const POINT &b) 16 { 17 return a.x < b.x; 18 } 19 bool cmpy(const POINT &a, const POINT &b) 20 { 21 return a.y < b.y; 22 } 23 double dis(const POINT &a, const POINT &b) 24 { 25 return sqrt((a.x-b.x) * (a.x-b.x) + (a.y-b.y) * (a.y-b.y)); 26 } 27 double min_dis(int a, int b, POINT *Y) 28 { 29 double ans = 1e8; 30 if (b-a <= 2) 31 { 32 for (int i = a; i < b; ++i) 33 { 34 for (int j = i+1; j <= b; ++j) 35 { 36 double temp = dis(X[i], X[j]); 37 if (ans > temp) 38 ans = temp; 39 } 40 } 41 return ans; 42 } 43 int mid = (a+b) / 2; 44 POINT *Yl = new POINT[mid-a+1]; 45 POINT *Yr = new POINT[b-mid]; 46 int i, j, k, ind; 47 for (i = 0, j = 0, k = 0; i <= b-a; ++i) 48 { 49 if (Y[i].index <= mid) Yl[j++] = Y[i]; 50 else Yr[k++] = Y[i]; 51 } 52 double left_min = min_dis(a, mid, Yl); 53 double right_min = min_dis(mid+1, b, Yr); 54 ans = min(left_min, right_min); 55 double line = X[mid].x; 56 for (i = 0, ind = 0; i <= b-a; ++i) 57 { 58 if (fabs(Y[i].x - line) < ans) 59 Y[ind++] = Y[i]; 60 } 61 for (i = 0; i < ind - 1; ++i) 62 { 63 for (j = i+1; j <= i+7 && j < ind; ++j) 64 { 65 double temp = dis(Y[i], Y[j]); 66 if (ans > temp) 67 ans = temp; 68 } 69 } 70 delete []Yl; 71 delete []Yr; 72 return ans; 73 } 74 int main() 75 { 76 int n, i; 77 while (scanf("%d", &n), n) 78 { 79 for (i = 0; i < n; ++i) 80 X[i].input(); 81 sort(X, X+n, cmpx); 82 for (i = 0; i < n; ++i) 83 X[i].index = i; 84 memcpy(Y, X, n * sizeof(POINT)); 85 sort(Y, Y+n, cmpy); 86 printf("%.2lf\n", min_dis(0, n-1, Y) / 2); 87 } 88 return 0; 89 } 最后输出半径,要除以2.