Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <bits/stdc++.h>
- using namespace std;
- struct point
- {
- int x, y;
- };
- bool compare1 (const point &a, const point &b)
- {
- return a.x>b.x;
- }
- bool compare2 (const point &a, const point &b)
- {
- return a.y>b.y;
- }
- double dist(point a, point b)
- {
- return sqrt((a.x-b.x)*(a.x-b.x)+(a.y-b.y)*(a.y-b.y));
- }
- double dist2(point P[], int n)
- {
- double minn=10000.0;
- for (int i=0; i<n; i++)
- {
- for (int j=i+1; j<n; j++)
- {
- if (dist(P[i], P[j]) < minn)
- {
- minn = dist(P[i], P[j]);
- }
- }
- }
- return minn;
- }
- double stripClosest (point strip[], int n, float d)
- {
- float minn = d;
- for (int i=0; i<n; i++)
- {
- for (int j=i+1; j<n && (strip[j].y-strip[i].y)<minn; j++)
- {
- if (dist(strip[i],strip[j]) < minn)
- {
- minn=dist(strip[i], strip[j]);
- }
- }
- }
- return minn;
- }
- double closestUtil(point Px[], point Py[], int n)
- {
- if (n <= 3) return dist2(Px, n);
- int mid = n/2;
- point midpoint = Px[mid];
- point PyL[mid+1];
- point PyR[n-mid-1];
- int l=0, r=0;
- for (int i=0; i<n; i++)
- {
- if (Py[i].x <= midpoint.x) PyL[l++] = Py[i];
- else PyR[r++] = Py[i];
- }
- double dl = closestUtil (Px, PyL, mid);
- double dr = closestUtil (Px + mid, PyR, n-mid);
- double d = min(dl, dr);
- point strip[n];
- int j=0;
- for (int i=0; i<n; i++)
- {
- if (abs(Py[i].x-midpoint.x)<d)
- {
- strip[j] = Py[i];
- j++;
- }
- }
- return min(d, stripClosest(strip, j, d) );
- }
- double closest(point P[], int n)
- {
- point Px[n], Py[n];
- for (int i=0; i<n; i++)
- {
- Px[i]=P[i];
- Py[i]=P[i];
- }
- sort (Px, Px+n, compare1);
- sort (Py, Py+n, compare2);
- return closestUtil(Px, Py, n);
- }
- int main()
- {
- int n, x, y;
- scanf("%d", &n);
- point P[n];
- for (int i=0; i<n; i++)
- {
- scanf("%d%d", &P[i].x, &P[i].y);
- }
- double ans = closest(P, n);
- printf("\nDistance is: %lf\n", ans);
- return 0;
- }
Add Comment
Please, Sign In to add comment