问题:最近对问题要求在包含n个点的集合中找出距离最近的两个点。在空中交通控制问题中,若将飞机作为空间移动的一个点来处理,则具有最大碰撞危险的两架飞机,就是这个空间中最接近的一对点。这类问题是几何中研究的基本问题之一。
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <math.h>
#define N 10
struct PointType
{
int x, y;
};
void CreatPot (struct PointType pot[], int n);
double MinPot (struct PointType pot[],int n, int *p, int *q);
void PrintPot (struct PointType pot[],int n);
int main()
{
struct PointType pot[N];
int i,minI,minJ;
double minDist;
CreatPot(pot,N);
PrintPot(pot,N);
minDist = MinPot(pot, N, &minI,&minJ);
printf("最近点(%2d, %2d)%5.2f\n",minI,minJ,minDist);
return 0;
}
void CreatPot(struct PointType pot[],int n)
{
int i;
srand(time(NULL));
for(i=0;i<n;i++)
{
pot[i].x =rand() % 100;
pot[i].y =rand() % 100;
}
}
void PrintPot(struct PointType pot[],int n)
{
int i;
printf("产生的随机点是:\n");
for(i=0;i<n;i++)
{
printf("%2d (%2d, %2d)\t",i+1,pot[i].x,pot[i].y);
if ((i+1)%5==0)
printf("\n");
}
}
double MinPot (struct PointType pot[], int n,int *p,int *q)
{
int i,j,minI,minJ,tempx,tempy;
int dist,minDist = 1000;
for(i=0;i<n;i++)
for(j=0;j<i;j++)
{
tempx=pot[i].x-pot[j].x;
tempy=pot[i].y-pot[j].y;
dist= tempx*tempx + tempy*tempy;
if(dist<minDist)
{
minDist = dist; minI=i+1;minJ=j+1;
}
}
*p = minI; *q=minJ;
return sqrt(minDist);
}
集合中找出距离最近的两个点