alg_problem: number_of_disc_intersections

圆盘交叠算法
本文介绍了一种计算二维平面上圆盘交叠数量的算法。该算法通过输入一系列整数来确定每个圆盘的半径,并据此计算出任意两个圆盘之间的交叠情况。文章提供了一个具体的C++实现示例,可用于解决类似的实际问题。

Given an array A of N integers we draw N discs in a 2D plane, such that i-th disc has center in (0,i) and a radius A[i]. We say that k-th disc and j-th disc intersect, if $k\not =j$ and k-th and j-th discs have at least one common point.

Write a function

int number_of_disc_intersections(int[] A);

which given an array A describing N discs as explained above, returns the number of pairs of intersecting discs. For example, given N=6 and


\begin{displaymath}A[0]=1 A[1]=5 A[2]=2 A[3]=1 A[4]=4 A[5]=0\end{displaymath}

there are 11 pairs of intersecting discs:

    0th and 1st
0th and 2nd
0th and 4th
1st and 2nd
1st and 3rd
1st and 4th
1st and 5th
2nd and 3rd
2nd and 4th
3rd and 4th
4th and 5th

so the function should return 11.

The function should return -1 if the number of intersecting pairs exceeds 10,000,000. The function may assume that N does not exceed 10,000,000.


 

#include <stdio.h>
#include <vector>

int number_of_disc_intersections ( const std::vector<int> &A ) {
   // write your code here
    size_t n = A.size();
    if(n==0) return -1;
    

    long long num=0;
    for(size_t i=0; i<n; i++)
    {
        for(size_t j=i+1; j<n; j++)
        {
            if( j-i<= A[i]+A[j] /*&& j -i + A[i] >= A[j] && j-i + A[j] >= A[i] */)
            {
                //printf("%d %d\n", i, j);
                num++;
                if(num>=10000000)
                    return -1;
            }
        }
    }

    return num;
}

int main()
{
    int a[]={1,5,2,1,4,0};
    std::vector<int> A(a, a+sizeof(a)/sizeof(a[0]));
    int i=number_of_disc_intersections(A);
    printf("%d\n",i);
}

 

 

http://stackoverflow.com/questions/4801242/algorithm-to-calculate-number-of-intersecting-discs

 

http://www.devcomments.com/q490073/Algorithm-to-calculate-number-intersecting-discs
 

 

转载于:https://www.cnblogs.com/cutepig/archive/2011/02/17/1956811.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值