- #include <stdio.h>
- //rand() and srand()
- #include <stdlib.h>
- #include <time.h>
- //sqrt()
- #include <math.h>
- //INT_MAX
- #include <limits.h>
- #define distance(x1,y1,x2,y2) /
- sqrt((x1-x2)*(x1-x2) + (y1-y2)*(y1-y2))
- #define MAX 10 //生成点的个数
- struct point
- {
- int x;
- int y;
- }point[MAX];
- struct pair
- {
- int point1;
- int point2;
- int min_distance;
- };
- void init_point(struct point *p);
- void show_point(struct point *p);
- struct pair closest_pair(struct point *p);
- int main(void)
- {
- struct pair point_pair;
- init_point(point);
- show_point(point);
- point_pair = closest_pair(point);
- printf("/nThe closest points are point %d and point %d./n", point_pair.point1+1, point_pair.point2+1 );
- printf("The distance is %d/n", point_pair.min_distance);
- return 0;
- }//main()
- void init_point(struct point *p)
- {
- int i;
- srand(time(NULL));
- for (i=0; i<MAX; i++)
- {
- p[i].x = rand()%100;
- p[i].y = rand()%100;
- }//for
- }//init_point()
- void show_point(struct point *p)
- {
- int i;
- for (i=0; i<MAX; i++)
- {
- printf("point[%d]/t(%d,%d)/n", i+1, p[i].x,p[i].y);
- }//for
- }//show_point()
- struct pair closest_pair(struct point *p)
- {
- int i,j;
- int temp;
- struct pair point_pair;
- point_pair.min_distance = INT_MAX;
- for (i=0; i<MAX-1; i++)
- {
- for (j=i+1; j<MAX; j++)
- {
- temp = distance(p[i].x,p[i].y,p[j].x,p[j].y);
- if (temp < point_pair.min_distance)
- {
- point_pair.min_distance = temp;
- point_pair.point1=i;
- point_pair.point2=j;
- }//if
- }//inner_for
- }//for()
- return point_pair;
- }//closest_pair()
最近点对(蛮力法)
最新推荐文章于 2020-04-21 11:50:07 发布