二分法搜索的应用

二分法是一个应用比较广泛的算法,但是也因此往往被我们忽略,比如这蓝桥杯的倒数第二题,注意线性时间枚举的超时的可能性,以防万一使用二分会保险一点,今天之所以要讲这个,是因为在poj上做到了几道相似的题,所以我觉得有必要总结一下,用三道例题阐述一下:

Cable master POJ - 1064
Inhabitants of the Wonderland have decided to hold a regional programming contest. The Judging Committee has volunteered and has promised to organize the most honest contest ever. It was decided to connect computers for the contestants using a “star” topology - i.e. connect them all to a single central hub. To organize a truly honest contest, the Head of the Judging Committee has decreed to place all contestants evenly around the hub on an equal distance from it.
To buy network cables, the Judging Committee has contacted a local network solutions provider with a request to sell for them a specified number of cables with equal lengths. The Judging Committee wants the cables to be as long as possible to sit contestants as far from each other as possible.
The Cable Master of the company was assigned to the task. He knows the length of each cable in the stock up to a centimeter,and he can cut them with a centimeter precision being told the length of the pieces he must cut. However, this time, the length is not known and the Cable Master is completely puzzled.
You are to help the Cable Master, by writing a program that will determine the maximal possible length of a cable piece that can be cut from the cables in the stock, to get the specified number of pieces.

Input
The first line of the input file contains two integer numb ers N and K, separated by a space. N (1 = N = 10000) is the number of cables in the stock, and K (1 = K = 10000) is the number of requested pieces. The first line is followed by N lines with one number per line, that specify the length of each cable in the stock in meters. All cables are at least 1 meter and at most 100 kilometers in length. All lengths in the input file are written with a centimeter precision, with exactly two digits after a decimal point.

Output
Write to the output file the maximal length (in meters) of the pieces that Cable Master may cut from the cables in the stock to get the requested number of pieces. The number must be written with a centimeter precision, with exactly two digits after a decimal point.
If it is not possible to cut the requested number of pieces each one being at least one centimeter long, then the output file must contain the single number “0.00” (without quotes).

Sample Input
4 11
8.02
7.43
4.57
5.39
Sample Output
2.00
这道题,首先第一点预处理是,题目给的数据是浮点数,为了防止产生精度误差,只要把它转化成3位整数即可,然后我们先要确定能剪的长度的上下界,即0.01到输入样例的中所有长度的最大值(假设只要一个布条),分析可以知道,如果x满足能得到k个布条,那么,小于x的值均满足,所以这个用二分非常合适
代码

import java.util.Scanner;

public class Main 
{
    static int k,a[];
    public static void main(String[]args)
    {
        Scanner sc=new Scanner(System.in);

        int n=sc.nextInt();
        k=sc.nextInt();
        a=new int[n];
        int max=-1;
        for(int i=0;i<n;i++)
        {
            a[i]=(int)(sc.nextDouble()*100);//转化为整数
            if(max<a[i])
                max=a[i];//寻找最大上界
        }

        int l=1;
        int r=max;//依次作为左右的两边
        while(l<=r)
        {
            int m=(l+r)/2;
            if(check(m))
                l=m+1;//使得最终必然使得l>r
            else
                r=m-1;//使得最终必然使得l>r 
        }
        l-=1;//这个得好好说一说
        //假设x满足check函数,那么x左边都不需要看了,但是x不一定是最大值,所以我们要往右边去找,那么x就会加一,但是假设x恰好是最大值,那么x的右边的值均不成立,此时保证l里存的值一直不会改变,直至循环终止
        System.out.printf("%.2f",l/100.0);//保留两位小数输出即可
    }
    static boolean check(int x)//判断x是否能使得k个的布条
    {
        int count=0;
        for(int i=0;i<a.length;i++)
        {
            count+=a[i]/x;
            if(count>=k)
                return true;
        }
        return false;
    }
}

分巧克力-蓝桥杯
儿童节那天有K位小朋友到小明家做客。小明拿出了珍藏的巧克力招待小朋友们。
小明一共有N块巧克力,其中第i块是Hi x Wi的方格组成的长方形。
为了公平起见,小明需要从这 N 块巧克力中切出K块巧克力分给小朋友们。切出的巧克力需要满足:
1. 形状是正方形,边长是整数
2. 大小相同
例如一块6x5的巧克力可以切出6块2x2的巧克力或者2块3x3的巧克力。
当然小朋友们都希望得到的巧克力尽可能大,你能帮小Hi计算出最大的边长是多少么?
输入
第一行包含两个整数N和K。(1 <= N, K <= 100000)
以下N行每行包含两个整数Hi和Wi。(1 <= Hi, Wi <= 100000)
输入保证每位小朋友至少能获得一块1x1的巧克力。
输出
输出切出的正方形巧克力最大可能的边长。
样例输入:
2 10
6 5
5 6
样例输出:
2
其实你可以发现此题和第一道题是完全一样
唯一的不同就是那个check函数,我就写一下这个check函数:

static boolean check(int x)//设H和W数组存的是第i个巧克力的高和宽
{
    int count=0;
    for(int i=0;i<a.length;i++)
    {
        count+=H[i]/x*W[i]/x;//其实连check函数都是差不多的
        if(count>=K)
            return true;
    }
    return false;
}

Aggressive cows POJ - 2456
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
    Sample Output
    3
    同样的,先去确定上下界,最近距一定是1,最远的是最大值节减去最小值,问题的关键是这个check函数改怎么写,这里我们用贪心的思想
    我们把这些牛舍先从小到大排序,那么最小值一定是属于要选的牛舍,反正法,假设牛舍的最小距离为x,设集合set是满足条件的一个集合且不包括a[0](最小值),那么我任选梁个值从set,设为t1和t2,假设(t2>t1),则t2-t1>=x,那么t2-a[0]>=x也必然满足,因为t1>a[0]。
    接下我们只要排除a[0],区寻找下一个除a[0]以外最小的切合法的牛舍,最终的从局部最优到全局最优。
    代码:
import java.util.Arrays;
import java.util.Scanner;

public class Main 
{
    static int m,a[];
    public static void main(String[]args)
    {
        Scanner sc=new Scanner(System.in);
        int n=sc.nextInt();
        m=sc.nextInt();
        a=new int[n];
        for(int i=0;i<n;i++)
            a[i]=sc.nextInt();
        Arrays.sort(a);//排序
        if(m==1)
        {
            System.out.println(1);
            return;
        }//如果是1直接输出,因为两个牛舍不会有相同的坐标
        int l=1;
        int r=a[a.length-1]-a[0];//上下界
        while(l<=r)
        {
            int m=(l+r)/2;
            if(check(m))
            {
                l=m+1;
            }
            else
                r=m-1;
        }
        l-=1;
        System.out.println(l);

    }
    static boolean check(int d)
    {
        int count=1;
        int target=a[0];//target是作为入选目标,第一个当然a[0]
        for(int i=1;i<a.length;i++)
        {
            if(a[i]-target>=d)//如果满足,则a[i]入选并且,作为下一次比较的对象。
            {
                count++;
                if(count==m)
                    return true;
                target=a[i];
            }
        }
        return false;
    }
}

从这几道题可以看出,二分的关键核心是怎么实现check函数,这个函数直接决定题目的难度
peace&love

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值