algorithmcomputational-geometryclosest-points

Sweepline algorithm


I am trying to solve problem CLOPPAIR on spoj in which i have to find the minimum euclidian distance between two points and print the indices of these two points also. I tried to do this using sweepline but still i am getting T.L.E .Can please someone help me?

Here is my code http://ideone.com/Tzy5Au

#include <iostream>
#include <bits/stdc++.h>
using namespace std;
class node{
    public:
    int idx;
    int x;
    int y;
    node(int xx=0,int yy=0,int ii=0){
        idx=ii;
        x=xx;
        y=yy;
    }
    friend bool operator<(node a,node b);
};
bool operator<(node a,node b){
    return(a.y<b.y);
}
bool cmp_fn(node a,node b){
    return(a.x<b.x);
}
void solve(node pts[],int n){
    int start,last;
    int left =0;
    double best=1000000000,v;
    sort(pts,pts+n,cmp_fn);
    set<node>box;
    box.insert(pts[0]);
    for(int i=1;i<n;i++){
        while(left<i && pts[i].x-pts[left].x >best){
            box.erase(pts[i]);
            left++;
        }
        for(typeof(box.begin())it=box.begin();it!=box.end() && pts[i].y+best>=it->y;it++){
            v=sqrt(pow(pts[i].y - it->y, 2.0)+pow(pts[i].x - it->x, 2.0));
            if(v<best){
                best=v;
                start=it->idx;
                last=pts[i].idx;
                if(start>last)swap(start,last);
            }
        }
        box.insert(pts[i]);
    }
    cout<<start<<" "<<last<<" "<<setprecision(6)<<fixed<<best;
} 
int main(){
    int t,n,x,y;
    cin>>n;
    node pts[n];
    for(int i=0;i<n;i++){
        cin>>x>>y;
        pts[i]=node(x,y,i);
    }
    solve(pts,n);
    return 0;
}

Solution

  • The time complexity of your solution is O(N^2) in the worst case (for instance, it happens if all points have the same x). That's too much for the given constraints.

    However, it's possible to fix your solution. You should keep points sorted by the y-coordinate in a set and iterate only over the [s.upper_bound(curY) - curBest, s.upper_bound(curY) + curBest) range of the set inside the for loop that goes in x order. This way, the time complexity is O(N log N) in the worst case.