c++蛮力法求最近对问题

来源:互联网 发布:windows官方商城 编辑:程序博客网 时间:2024/04/30 18:18
#include <iostream>#include <math.h>#include <stdlib.h>using namespace std;#define M 10000struct P{    int x;    int y;};
#首先定义一个结构体,结构体的内容为点的x,y值
double ClosestPoints(int n,P a[],int &index1,int &index2){    double  d;    double  Dist=M;    for (int i=0;i<=n-2;i++)    {        for (int j=i+1;j<=n-1;j++)        {            d=(a[i].x-a[j].x)*(a[i].x-a[j].x)+(a[i].y-a[j].y)*(a[i].y-a[j].y);            if(d<=Dist)            {                Dist=d;                index1=i;                index2=j;            }        }    }    return Dist;}
#求最近对的函数.用一维数组求最近对的距离,返回的是距离的平方
int main(){    int i,j,r,g,s,e;    double w;    P a[M];    cout<<"输入坐标的个数:";    cin>>g;        for (r=1;r<=g;r++)        {            a[r].x=rand()%(g-23);            a[r].y=rand()%(g-345);        }        w=ClosestPoints(g,a,s,e);        cout<<"最近的两个点是:P1("<<a[s].x<<","<<a[s].y<<") P2("<<a[e].x<<","<<a[e].y<<")"<<endl;        cout<<"距离是:"<<sqrt(w)<<endl;        return 0;}
#调用ClosestPoints函数(注意传的参数)
#for循环的作用是输入点的个数,rand() % M 函数的作用是返回0--M-1的随机数,用rand函数不用一个一个输入点.

0 0