Akatsuki13

Closest Pair

Oct 28th, 2016
37
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.16 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2.  
  3. using namespace std;
  4.  
  5. struct point
  6. {
  7.     int x, y;
  8. };
  9.  
  10. bool compare1 (const point &a, const point &b)
  11. {
  12.     return a.x>b.x;
  13. }
  14.  
  15. bool compare2 (const point &a, const point &b)
  16. {
  17.     return a.y>b.y;
  18. }
  19.  
  20. double dist(point a, point b)
  21. {
  22.     return sqrt((a.x-b.x)*(a.x-b.x)+(a.y-b.y)*(a.y-b.y));
  23. }
  24.  
  25. double dist2(point P[], int n)
  26. {
  27.     double minn=10000.0;
  28.     for (int i=0; i<n; i++)
  29.     {
  30.         for (int j=i+1; j<n; j++)
  31.         {
  32.             if (dist(P[i], P[j]) < minn)
  33.             {
  34.                 minn = dist(P[i], P[j]);
  35.             }
  36.         }
  37.     }
  38.     return minn;
  39. }
  40.  
  41. double stripClosest (point strip[], int n, float d)
  42. {
  43.     float minn = d;
  44.     for (int i=0; i<n; i++)
  45.     {
  46.         for (int j=i+1; j<n && (strip[j].y-strip[i].y)<minn; j++)
  47.         {
  48.             if (dist(strip[i],strip[j]) < minn)
  49.             {
  50.                 minn=dist(strip[i], strip[j]);
  51.             }
  52.         }
  53.     }
  54.  
  55.     return minn;
  56. }
  57.  
  58. double closestUtil(point Px[], point Py[], int n)
  59. {
  60.     if (n <= 3) return dist2(Px, n);
  61.     int mid = n/2;
  62.     point midpoint = Px[mid];
  63.     point PyL[mid+1];
  64.     point PyR[n-mid-1];
  65.     int l=0, r=0;
  66.     for (int i=0; i<n; i++)
  67.     {
  68.         if (Py[i].x <= midpoint.x) PyL[l++] = Py[i];
  69.         else PyR[r++] = Py[i];
  70.     }
  71.     double dl = closestUtil (Px, PyL, mid);
  72.     double dr = closestUtil (Px + mid, PyR, n-mid);
  73.     double d = min(dl, dr);
  74.     point strip[n];
  75.     int j=0;
  76.     for (int i=0; i<n; i++)
  77.     {
  78.         if (abs(Py[i].x-midpoint.x)<d)
  79.         {
  80.             strip[j] = Py[i];
  81.             j++;
  82.         }
  83.     }
  84.     return min(d, stripClosest(strip, j, d) );
  85. }
  86.  
  87. double closest(point P[], int n)
  88. {
  89.     point Px[n], Py[n];
  90.     for (int i=0; i<n; i++)
  91.     {
  92.         Px[i]=P[i];
  93.         Py[i]=P[i];
  94.     }
  95.     sort (Px, Px+n, compare1);
  96.     sort (Py, Py+n, compare2);
  97.  
  98.     return closestUtil(Px, Py, n);
  99. }
  100.  
  101. int main()
  102. {
  103.     int n, x, y;
  104.     scanf("%d", &n);
  105.     point P[n];
  106.     for (int i=0; i<n; i++)
  107.     {
  108.         scanf("%d%d", &P[i].x, &P[i].y);
  109.     }
  110.     double ans = closest(P, n);
  111.     printf("\nDistance is: %lf\n", ans);
  112.     return 0;
  113. }
Add Comment
Please, Sign In to add comment