程序设计实例10.2—最近对问题并复现

问题:最近对问题要求在包含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);
 }

集合中找出距离最近的两个点

  • 6
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值