c - Algorithm to find shortest distance from a point in set A to points in set B -
there set n 3d points (x,y,z) , set b m 3d points (x,y,z). each point (xi,yi,zi) in set have find point in set b has minimum distance (xi,yi,zi).
my code running out of given time limit. please help.
#include<stdio.h> #include<stdlib.h> #include<math.h> long long np[50000][3],qp[50000][3]; int main() { long long n,q,i,j,d,ans,min; scanf("%lld",&n); for(i=0;i<n;i++) scanf("%lld%lld%lld",&np[i][0],&np[i][0],&np[i][2]); scanf("%lld",&q); for(i=0;i<q;i++) scanf("%lld%lld%lld",&qp[i][0],&qp[i][1],&qp[i][2]); for(i=0;i<q;i++) { ans=0; min=((qp[i][0]-np[0][0])*(qp[i][0]-np[0][0]))+((qp[i][1]-np[0][1])*(qp[i][1]-qp[0][1]))+((qp[i][2]-np[0][2])*(qp[i][2]-np[0][2])); for(j=0;j<n;j++) { d=((qp[i][0]-np[j][0])*(qp[i][0]-np[j][0]))+((qp[i][1]-np[j][1])*(qp[i][1]-qp[j][1]))+((qp[i][2]-np[j][2])*(qp[i][2]-np[j][2])); if(d<min) { ans=j; min=d; } } printf("%lld\n",ans); } return 0; }
you're using o(n^2) algo. doubt fast enough. ways faster, check out this article.
or more specifically, can use divide conquer approach described in article, relatively straightforward if you're comfortable recursion. since dealing z axis, you'll have extend algo described there use 2 dividing lines (one x axis, 1 y), it's going bit more complicated.
Comments
Post a Comment