4eyes4u

Closest pair in set of points

Feb 1st, 2017
177
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.75 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. const int N=1e5+10;
  5.  
  6. struct pt
  7. {
  8.     double x, y;
  9.     int idx;
  10.  
  11.     bool operator<(const pt &p) const
  12.     {
  13.         return (x<p.x || (x==p.x && y<p.y));
  14.     }
  15. };
  16.  
  17. pt a[N], aux[N];
  18. pair<pt, pt> pts;
  19. double sol=10000000.0;
  20. int n;
  21.  
  22. double dist (pt a, pt b)
  23. {
  24.     return sqrt((a.x-b.x)*(a.x-b.x)+(a.y-b.y)*(a.y-b.y));
  25. }
  26.  
  27. void update (pt a, pt b)
  28. {
  29.     double d=dist(a, b);
  30.     if (d<sol)
  31.     {
  32.         sol=d;
  33.         pts={a, b};
  34.     }
  35. }
  36.  
  37. void solve (int l, int r)
  38. {
  39.     if (l>=r) return;
  40.     if (r-l==1)
  41.     {
  42.         if (a[l].y>a[r].y) swap (a[l], a[r]); //preparing for merge sort
  43.         update (a[l], a[r]);
  44.         return;
  45.     }
  46.  
  47.     int mid=(l+r)/2;
  48.     double separator=a[mid].x; //vertical separating line
  49.  
  50.     solve (l, mid);
  51.     solve (mid+1, r);
  52.  
  53.     int L=l, R=mid+1, k=0;
  54.     while (L<=mid || R<=r) //merge sort
  55.     {
  56.         if (L>mid || (R<=r && a[R].y<a[L].y)) aux[k++]=a[R++];
  57.         else aux[k++]=a[L++];
  58.     }
  59.  
  60.     for (int i=l;i<=r;i++) a[i]=aux[i-l]; //sorted
  61.  
  62.     k=0;
  63.     for (int i=l;i<=r;i++) if (abs(a[i].x-separator)<sol) aux[k++]=a[i]; //getting rid of unnecessary points
  64.     for (int i=0;i<k;i++) //making better solution
  65.     {
  66.         for (int j=i+1;j<k;j++) //maximum 5 iterations
  67.         {
  68.             if (aux[j].y-aux[i].y>=sol) break;
  69.             update(aux[i], aux[j]);
  70.         }
  71.     }
  72. }
  73.  
  74. int main()
  75. {
  76.     scanf ("%d", &n);
  77.     for (int i=1;i<=n;i++)
  78.     {
  79.         scanf ("%lf%lf", &a[i].x, &a[i].y);
  80.         a[i].idx=i-1;
  81.     }
  82.  
  83.     sort (a+1, a+n+1);
  84.  
  85.     solve(1, n);
  86.  
  87.     cout << min(pts.first.idx, pts.second.idx) << " " << max(pts.first.idx, pts.second.idx) << " " << fixed << setprecision(6) << sol;
  88.  
  89.     return 0;
  90. }
Advertisement
Add Comment
Please, Sign In to add comment