最近点对(蛮力法)

 

  1. #include <stdio.h>
  2. //rand() and srand()
  3. #include <stdlib.h>
  4. #include <time.h>
  5. //sqrt()
  6. #include <math.h>
  7. //INT_MAX
  8. #include <limits.h>
  9. #define distance(x1,y1,x2,y2)   /
  10.   sqrt((x1-x2)*(x1-x2) + (y1-y2)*(y1-y2))
  11. #define MAX 10          //生成点的个数
  12. struct point
  13. {
  14.   int x;
  15.   int y;
  16. }point[MAX];
  17. struct pair
  18. {
  19.   int point1;
  20.   int point2;
  21.   int min_distance;
  22. };
  23. void init_point(struct point *p);
  24. void show_point(struct point *p);
  25. struct pair closest_pair(struct point *p);
  26. int main(void)
  27. {
  28.   struct pair point_pair;
  29.   init_point(point);
  30.   show_point(point);
  31.   point_pair = closest_pair(point);
  32.   
  33.   printf("/nThe closest points are point %d and point %d./n", point_pair.point1+1, point_pair.point2+1 );
  34.   printf("The distance is %d/n", point_pair.min_distance);
  35.   return 0;
  36. }//main()
  37. void init_point(struct point *p)
  38. {
  39.   int i;
  40.   srand(time(NULL));
  41.   for (i=0; i<MAX; i++)
  42.   {
  43.     p[i].x = rand()%100;
  44.     p[i].y = rand()%100;
  45.   }//for
  46. }//init_point()
  47. void show_point(struct point *p)
  48. {
  49.   int i;
  50.   for (i=0; i<MAX; i++)
  51.   {
  52.     printf("point[%d]/t(%d,%d)/n", i+1, p[i].x,p[i].y);
  53.   }//for
  54. }//show_point()
  55. struct pair closest_pair(struct point *p)
  56. {
  57.   int i,j;
  58.   int temp;
  59.   struct pair point_pair;
  60.   point_pair.min_distance = INT_MAX;
  61.   for (i=0; i<MAX-1; i++)
  62.   {
  63.     for (j=i+1; j<MAX; j++)
  64.     {
  65.       temp = distance(p[i].x,p[i].y,p[j].x,p[j].y);
  66.       if (temp < point_pair.min_distance)
  67.       {
  68.         point_pair.min_distance = temp;
  69.         point_pair.point1=i;
  70.         point_pair.point2=j;
  71.       }//if
  72.     }//inner_for
  73.   }//for()
  74.   return point_pair;
  75. }//closest_pair()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值