二分法的使用

关于二分法的详细使用

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

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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值