天之道

享受编程的乐趣。
posts - 118, comments - 7, trackbacks - 0, articles - 0
  C++博客 :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理

最近点对的计算

Posted on 2012-08-14 21:39 hoshelly 阅读(301) 评论(0)  编辑 收藏 引用 所属分类: ProgrammingDS && Algorithm
编写程序,对于N个随机产生的单位正方形中的点,统计可以被长度小于d的直线连结的点对数。

程序如下:

typedef structfloat x; float y; } point; //定义点的数据类型
float distance(point,point); //两点之间距离函数
float distance(point a,point b)

   float dx= a.x - b.x, dy= a.y - b.y;
   return sqrt(dx*dx + dy*dy);
}
//以上为头文件 Point.h 的内容



#include<stdio.h> 
#include<stdlib.h>
#include<math.h>
#include "Point.h"
float randFloat()
{  return 1.0*rand()/RAND_MAX; } //产生随机数的函数
int main()
{
    float d,N;
    int i,j,cnt=0;
    scanf("%f%f",&d,&N); //d为要求两点之间距离小于的长度,N为测试的点 
    point *a = (point *)malloc(sizeof(point)*N); //动态生成数据类型为point的数组a
    for(i=0;i<N;i++)
{
a[i].x = randFloat(); a[i].y = randFloat(); 
}
    for(i=0;i<N;i++)
        for(j=i+1;j<N;j++)
            if(distance(a[i],a[j])<d) //如果两点之间的距离小于d,那么cnt加1
                     cnt++;
    printf("%d edges shorter than %f\n",cnt,d); //输出有多少条边的长度小于d
    return 0;
}

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理