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

二分法的使用

2013年12月05日 ⁄ 综合 ⁄ 共 1353字 ⁄ 字号 评论关闭

关于二分法的详细使用

首先我第一次接触二分法是二分法的查找,

int BinaraySearch(int *array,int target,
                           unsigned int i,unsigned int n)
{

    int const j=i+n/2;
    if(n==1)
    {
            return i;
    }
    else
    {
    if(array[j]<=target)
        return BinaraySearch(array,target,j,n/2);
    else
        return BinaraySearch(array,target,i,n/2);
    }
}

这是一个相当简单的二分法的使用,无非就是给定一个已排序的数组,然后每次折中查找,直到找到相应的target值返回数组下标

接下来我接触到的对二分法的使用是使用二分法求解:

用二分法实现开根号求解:

 double u, d, k, n;
    scanf("%lf", &n);
    u = 10000000.0;
    d = 0;
    k=0;
    while( u - d > 0.000001)
    {
        printf("%lf %lf %lf %lf\n",u,d,k,k*k*k*k*k);
        k = (u + d) / 2;
        if ( k * k * k * k * k < n) d = k;
        else u = k;
    }

这段代码实现的功能也就是对n实现开5次根号,精度在0.000001之内,,,u表示的是二分的上限,d表示的二分下线,,,,,k值也就是二分值,不断根据k值的范围重新设定上限和下限,最终开出根号k值,

接下来是使用二分法进行排序:由于二分排序的平均时间是O(n2),所以本人也觉得吧!没什么用处的!

最后发一道POJ上的二分的题ID2456

Description

Farmer John has built a new long barn, with N (2 <= N <= 100,000) stalls. The stalls are located along a straight line at positions x1,...,xN (0 <= xi <= 1,000,000,000).

His C (2 <= C <= N) cows don't like this barn layout and become aggressive towards each other once put into a stall. To prevent the cows from hurting each other, FJ want to assign the cows to the stalls, such that the minimum distance between any two of them
is as large as possible.  What is the largest minimum distance?

Input

* Line 1: Two space-separated integers: N and C

* Lines 2..N+1: Line i+1 contains an integer stall location, xi

Output

* Line 1: One integer: the largest minimum distance

Sample Input

5 3
1
2
8
4
9

抱歉!评论已关闭.