现在的位置: 首页 > 综合 > 正文

最近点对(蛮力法)

2013年01月02日 ⁄ 综合 ⁄ 共 1497字 ⁄ 字号 评论关闭
 
  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()

抱歉!评论已关闭.