1. 程式人生 > >c++蠻力法求最近對問題

c++蠻力法求最近對問題

#include <iostream>
#include <math.h>
#include <stdlib.h>
using namespace std;
#define M 10000
struct 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函式不用一個一個輸入點.