从有序数组中查找某个值

  • 问题描述:给定长度为n的单调不下降数列a0,…,an-1和一个数k,求满足ai≥k条件的最小的i。不存在则输出n。
  • 限制条件:
    1≤n≤106
    0≤a0≤a1≤…≤an-1<109
    0≤k≤109
  • 分析:二分搜索。STL以lower_bound函数的形式实现了二分搜索。
  • 代码:
     #include <cstdio>
    #include <cctype>
    #include <algorithm>
    #define num s-'0' using namespace std; const int MAX_N=;
    const int INF=0x3f3f3f3f;
    int n,k;
    int a[MAX_N]; void read(int &x){
    char s;
    x=;
    bool flag=;
    while(!isdigit(s=getchar()))
    (s=='-')&&(flag=true);
    for(x=num;isdigit(s=getchar());x=x*+num);
    (flag)&&(x=-x);
    } void write(int x)
    {
    if(x<)
    {
    putchar('-');
    x=-x;
    }
    if(x>)
    write(x/);
    putchar(x%+'');
    } int search(int); int main()
    {
    read(n);read(k);
    for (int i=; i<n; i++) read(a[i]);
    int p = search(k);
    write(p);
    putchar('\n');
    write(lower_bound(a,a+n,k)-a);
    putchar('\n');
    } int search(int k)
    {
    int l=-, r=n-;
    while (r-l>)
    {
    int mid=(r+l)/;
    if (a[mid]>=k) r=mid;
    else l=mid;
    }
    return r;
    }

    lower_bound


假定一个解并判断是否可行

对于任意满足C(x)的x,如果所有的x'≥x也满足C(x')的话,我们就可以用二分搜索来求得最小的x。首先我们将区间的左端点初始化为不满足C(x)的值,右端点初始化为满足C(x)的值,然后每次取中点mid=(lb+ub)/2,判断C(mid)是否满足并缩小范围,直到(lb,ub]足够小了为止,最后ub就是要求的最小值。最大化的问题也可以用同样的方法求解。

Cable master(POJ 1064)

  • 原题如下:

    Cable master
    Time Limit: 1000MS   Memory Limit: 10000K
    Total Submissions: 65114   Accepted: 13413

    Description

    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
  • 分析:二分搜索。套用二分搜索的模型,令条件C(x):=可以得到K条长度为x的绳子,则问题变成了求满足C(x)条件的最大的x。在区间初始化时,只需使用充分大的数INF(>MAXL)作为上界即可:lb=0, ub=INF。现在只要能高效地判断C(x)即可,由于长度为Li的绳子最多可以切出floor(Li/x)段长度为x绳子,因此C(x)=(floor(Li/x)的总和是否大于或等于K),这可以在O(n)内被判断出来
  • 代码:
     #include <cstdio>
    #include <cctype>
    #include <algorithm>
    #include <cmath>
    #define num s-'0' using namespace std; const int MAX_N=;
    const int INF=;
    int n,k;
    double L[MAX_N]; void read(int &x){
    char s;
    x=;
    bool flag=;
    while(!isdigit(s=getchar()))
    (s=='-')&&(flag=true);
    for(x=num;isdigit(s=getchar());x=x*+num);
    (flag)&&(x=-x);
    } void write(int x)
    {
    if(x<)
    {
    putchar('-');
    x=-x;
    }
    if(x>)
    write(x/);
    putchar(x%+'');
    } double search();
    bool C(double x); int main()
    {
    read(n);read(k);
    for (int i=; i<n; i++) scanf("%lf", &L[i]);
    double p = search();
    printf("%.2f", floor(p*)/);
    putchar('\n');
    } bool C(double x)
    {
    int sum=;
    for (int i=; i<n; i++)
    {
    sum+=(int)(L[i]/x);
    if (sum>=k) return true;
    }
    return false;
    } double search()
    {
    double lb=, ub=INF;
    //while (ub-lb>0.001)
    for (int i=; i<; i++)
    {
    double mid=(lb+ub)/;
    if (C(mid)) lb=mid;
    else ub=mid;
    }
    return ub;
    }

    Cable master

  • PS:关于二分搜索法的结束的判定,上面的代码指定了循环次数作为终止条件,1次循环可以把区间的范围缩小一半,100次循环则可以达到10-30的精度范围,基本上是没有问题的,除此之外,也可以把终止条件设为像上面注释中(ub-lb)>EPS那样,指定一个区间的大小,在这种情况下,如果EPS取得太小了,可能会因为浮点小数精度的原因导致陷入死循环,要小心这一点。

最大化最小值

Aggressive cows(POJ 2456)

  • 原题如下:

    Aggressive cows
    Time Limit: 1000MS Memory Limit: 65536K
    Total Submissions: 20518 Accepted: 9737

    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

    Sample Output

    3

    Hint

    OUTPUT DETAILS:

    FJ can put his 3 cows in the stalls at positions 1, 4 and 8, resulting in a minimum distance of 3.

    Huge input data,scanf is recommended.

  • 分析:类似的最大化最小值或者最小化最大值的问题,通常用二分搜索法解决。
    我们定义:C(d):=可以安排牛的位置使得最近的两头牛的距离不小于d,那么问题就变成了求满足C(d)的最大的d。另外,最近的间距不小于d也可以说成是所有牛的间距都不小于d,因此就有C(d)=可以安排牛的位置使得任意的牛的间距都不小于d,这个问题的判断使用贪心法就可以解决。
  • 代码:
     #include <cstdio>
    #include <cctype>
    #include <algorithm>
    #include <cmath>
    #define num s-'0' using namespace std; const int MAX_N=;
    const int INF=0x3f3f3f3f;
    int N,M;
    int x[MAX_N]; void read(int &x){
    char s;
    x=;
    bool flag=;
    while(!isdigit(s=getchar()))
    (s=='-')&&(flag=true);
    for(x=num;isdigit(s=getchar());x=x*+num);
    (flag)&&(x=-x);
    } void write(int x)
    {
    if(x<)
    {
    putchar('-');
    x=-x;
    }
    if(x>)
    write(x/);
    putchar(x%+'');
    } bool C(int); int main()
    {
    read(N);read(M);
    for (int i=; i<N; i++) read(x[i]);
    sort(x, x+N);
    int lb=, ub=INF;
    while (ub-lb>)
    {
    int mid=(lb+ub)/;
    if (C(mid)) lb=mid;
    else ub=mid;
    }
    write(lb);
    putchar('\n');
    } bool C(int d)
    {
    int last=;
    for (int i=; i<M; i++)
    {
    int crt=last+;
    while (crt<N && x[crt]-x[last]<d) crt++;
    if (crt==N) return false;
    last=crt;
    }
    return true;
    }

    Aggressive cows


最大化平均值

  • 问题描述:有n个物品的重量和价值分别是wi和vi。从中选出k个物品使得单位重量的价值最大。
  • 限制条件:
    1≤k≤n≤104
    1≤wi,vi≤106
  • 分析:定义:条件C(x):=可以选择使得单位重量的价值不小于x,因此,原问题就变成了求满足C(x)的最大的x。接下来就是C(x)可行性的判断了,假设选了某个物品的集合S,那么它们的单位重量的价值是∑vi/∑wi,因此就是判断是否存在S满足∑vi/∑wi≥x,将不等式变形,得到∑(vi-x*wi)≥0,因此,可以对(vi-x*wi)的值进行排序贪心地进行选取,故C(x)=((vi-x*wi)从大到小排列中的前k个的和不小于0),每次判断的复杂度是O(nlogn)
  • 代码:
     #include <cstdio>
    #include <cctype>
    #include <algorithm>
    #include <cmath>
    #define num s-'0' using namespace std; const int MAX_N=;
    const int INF=0x3f3f3f3f;
    int n,k;
    int v[MAX_N],w[MAX_N];
    double y[MAX_N]; void read(int &x){
    char s;
    x=;
    bool flag=;
    while(!isdigit(s=getchar()))
    (s=='-')&&(flag=true);
    for(x=num;isdigit(s=getchar());x=x*+num);
    (flag)&&(x=-x);
    } void write(int x)
    {
    if(x<)
    {
    putchar('-');
    x=-x;
    }
    if(x>)
    write(x/);
    putchar(x%+'');
    } bool C(double); int main()
    {
    read(n);read(k);
    for (int i=; i<n; i++)
    {
    read(w[i]);
    read(v[i]);
    }
    double lb=, ub=INF;
    for (int i=; i<; i++)
    {
    double mid=(lb+ub)/;
    if (C(mid)) lb=mid;
    else ub=mid;
    }
    printf("%.2f\n",ub);
    } bool C(double x)
    {
    for (int i=; i<n; i++)
    {
    y[i]=v[i]-x*w[i];
    }
    sort(y,y+n);
    double sum=;
    for (int i=; i<k; i++)
    {
    sum+=y[n--i];
    }
    return sum>=;
    }

    最大化平均值

不光是查找值!"二分搜索"的更多相关文章

  1. 不光是查找值! "二分搜索"

    2018-11-14 18:14:15 二分搜索法,是通过不断缩小解的可能存在范围,从而求得问题最优解的方法.在程序设计竞赛中,经常会看到二分搜索法和其他算法相结合的题目.接下来,给大家介绍几种经典的 ...

  2. Linux输入输出重定向和文件查找值grep命令

    Linux输入输出重定向和文件查找值grep命令 一.文件描述符Linux 的shell命令,可以通过文件描述符来引用一些文件,通常使用到的文件描述符为0,1,2.Linux系统实际上有12个文件描述 ...

  3. 获取一个数组(vector)与查找值(value)的差最小绝对值的成员索引的算法

    代码如下: 函数作用:传递进来一个数组(vector),和一个需要查找的值(value),返回与value的差值绝对值最小的vector成员索引,若value不在vector范围中,则返回-1: in ...

  4. Python3基础 setdefault() 根据键查找值,找不到键会添加

    镇场诗: 诚听如来语,顿舍世间名与利.愿做地藏徒,广演是经阎浮提. 愿尽吾所学,成就一良心博客.愿诸后来人,重现智慧清净体.-------------------------------------- ...

  5. Python3基础 dict setdefault 根据键查找值,找不到键会添加

             Python : 3.7.0          OS : Ubuntu 18.04.1 LTS         IDE : PyCharm 2018.2.4       Conda ...

  6. java数组倒序查找值

    java语言里面没有arr[:-2]这种方式取值 只能通过  arr[arr.length-1-x]的方式取值倒数的 x(标示具体的某个值)

  7. Excel-vlookup(查找值,区域范围,列序号,0)如何固定住列序列号,这样即使区域范围变动也不受影响

    突然,发现VLOOKUP的列序列号并不会随着区域范围的改变而自动调节改变,只是傻瓜的一个数,导致V错值.所有,就想实现随表格自动变化的列序号. 方法一:在列序号那里,用函数得出永远想要的那个列在区域范 ...

  8. 9、Cocos2dx 3.0游戏开发三查找值小工厂方法模式和对象

    重开发人员的劳动成果,转载的时候请务必注明出处:http://blog.csdn.net/haomengzhu/article/details/27704153 工厂方法模式 工厂方法是程序设计中一个 ...

  9. [Database] 不知道表名和字段查找值=1234的数据.

      --如果表比较大,时间会比较长 DECLARE @searchValue NVARCHAR(50) SET @searchValue='1234' DECLARE @t TABLE ( rowNu ...

随机推荐

  1. SpringBoot整合Spring Security

    好好学习,天天向上 本文已收录至我的Github仓库DayDayUP:github.com/RobodLee/DayDayUP,欢迎Star,更多文章请前往:目录导航 前言 Spring Securi ...

  2. 基于token的会话保持机制

    session简介 做过Web开发的程序员应该对Session都比较熟悉,Session是一块保存在服务器端的内存空间,一般用于保存用户的会话信息. 用户通过用户名和密码登陆成功之后,服务器端程序会在 ...

  3. 2-1关闭和重启linux系统

    0x01 shutdown命令 语法:shutdown [选项][时间][警告信息] 选项 含义 -k 并不执行shutdown,只是发出警告信息 -r 重新启动系统 -h 关闭系统 -c 取消运行s ...

  4. 12. oracle 常用函数

    一.字符函数字符函数是oracle中最常用的函数,我们来看看有哪些字符函数:lower(char):将字符串转化为小写的格式.upper(char):将字符串转化为大写的格式.length(char) ...

  5. Protocol buffers--python 实践 简介以及安装与使用

    简介: Protocol Buffers以下简称pb,是google开发的一个可以序列化 反序列化object的数据交换格式,类似于xml,但是比xml 更轻,更快,更简单.而且以上的重点突出一个跨平 ...

  6. FinalShell远程连接工具推荐

    今天给大家推荐一个类似Xshell的工具FinalShell,这个工具也使用了很长时间了, Windows和Mac版本都有,方便连接虚拟机 可以很方便的上传文件,有兴趣可以试试这款软件. 地址:htt ...

  7. Asp.Net Core Swagger 接口分组(支持接口一对多暴露)

    开始之前,先介绍下swagger常用方法. services.AddSwaggerGen    //添加swagger中间件 c.SwaggerDoc  //配置swagger文档,也就是右上角的下拉 ...

  8. [FJOI2020]染色图的联通性问题 题解

    FJOI2020 D1T2 题目大意 给出一个由 $n$ 个点 $m$ 条边构成的染色无向图,求删去每一个点及与其相连的边后图中不连通的同色点对数量.$n,m\leq 10^5$. 思路分析 可以想到 ...

  9. 关于提高服务器的带宽策略bonding

    一:bonding的概念 所谓bonding就是将多块网卡绑定同一IP地址对外提供服务,可以实现网卡的带宽扩容.高可用或者负载均衡. 二:bonding的优势 1 网络负载均衡 2 提高带宽网络传输效 ...

  10. MD5加密,java String 转变成MD5 String 详细代码,工具类Android开发必备

    /** * MD5加码.32位 * @param inStr * @return */ public static String MD5(String inStr) { MessageDigest m ...