求n个坐标点中最近的两点的距离。。
要求第一行输入n,2<=n<=1000,接下去n行分别输入一个点的坐标。最后输出其中最近两个点的距离。(保留3为小数)
如:
Sample Input:
5
1.20 2.32
1.31 5.33
5.61 5.63
10.20 2.62
12.21 3.50
Sample Output
2.194
本人的思想,因为还没怎么学过算法,所以想着求出各个点的距离,再取最小的。代码如下:
#include<iostream>
#include<math.h>
#include<iomanip>
using namespace std;
int main()
{
int n;
cin>>n;
if(n>=2 && n<=1000)
{
int d=0,sum=0;
float temp,l,s;
for(int p=n-1;p>=1;p--)
{
sum+=p; //求出总共几个数据
}
float*c=new float[sum];
float*a=new float[n];
float*b=new float[n];
for(int i=0;i<n;i++)
{
cin>>a[i]>>b[i]; //输入点的坐标
}
for(int j=0;j<n-1;j++)
{
for(int k=n-1;k>=j+1;k--)
{
l=a[j]-a[k];
s=b[j]-b[k];
c[d]=sqrt(l*l+s*s);
d++;
}
}
temp=c[0];
for(int y=1;y<sum;y++)
{
if(temp>c[y])
{
temp=c[y]; //求最小距离
}
}
cout.setf(ios::fixed);
cout<<setprecision(3)<<temp<<endl;
delete[]a;
delete[]b;
delete[]c;
}
return 0;
}
这题感觉很简单,但是在我们学校的题库里面就是AC不掉,是他测试的数据在我这里不能得到正确的答案吗?求帮助,最好能给个比较好的算法。