新文章

2012年1月11日 星期三

[C++]Closest pair problem code

給定10點座標,x及y值界於0-100,找出最接近知兩點且求出距離。




#include <cstdlib>
#include <iostream>
#include<fstream>
#include<ctime>
#include <time.h>
#include<math.h>
using namespace std;
struct point
{
double x;
double y;
};

int main()
{
clock_t start, end;
point a[10];

int u;
start = clock();

//***********************************************************
//***********************************************************

srand((unsigned)time(0));
cout<<"Here is the point :"<<endl;
for (int i=0;i<10;i++)
{
a[i].x= u=rand()%100;

cout <<(i+1)<<". ("<<u;
a[i].y= u=rand()%100;
cout <<","<< u<<")"<<endl;

}
//***********************************************************
//***********************************************************
double dst=0,min;
int d1=0,d2=1;
min=((a[1].x)-(a[0].x))*((a[1].x)-(a[0].x))+((a[1].y)-(a[0].y))*((a[1].y)-(a[0].y));
for(int i=0;i<10;i++)
{
for(int j=i+1;j<10;j++)
{
dst=((a[j].x)-(a[i].x))*((a[j].x)-(a[i].x))+((a[j].y)-(a[i].y))*((a[j].y)-(a[i].y));

if(min>dst)
{
min=dst;
d1=i;
d2=j;
}
}

}
end  = clock();
cout << "Time required for execution: "
<< (double)(end-start)/CLOCKS_PER_SEC
<< " seconds." << "\n\n";
cout<<"The minimal distance :"<<sqrt(min)<<endl;
cout<<"Coordinate: ("<< a[d1].x <<","<<a[d1].y <<")";
cout<<" , ("<< a[d2].x <<","<<a[d2].y <<")"<<endl;
system("PAUSE");
return 0;

}

沒有留言:

張貼留言