从有序数组中查找某个值

  • 问题描述:给定长度为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. 论如何实现最强大脑黑白迭代(c++附代码)

    最近看了最强大脑,对节目中的黑白迭代很感兴趣,就自己写了一个500多行的程序.燃鹅,只实现了一部分功能,还非常简陋.无奈之下,我只好从网上下载了一份代码,然后自己稍加修改就成了一份半改编的代码. 虽然 ...

  2. 【ASP.NET Core学习】使用JWT认证授权

    概述 认证授权是很多系统的基本功能 , 在以前PC的时代 , 通常是基于cookies-session这样的方式实现认证授权 , 在那个时候通常系统的用户量都不会很大, 所以这种方式也一直很好运行, ...

  3. windows下mongoDB的下载和安装

    1.进入mongoDB官网,官网地址:https://www.mongodb.com 2.  点击Try free按钮,进入下载页面 3.点击download进行下载:下载完成如下图: 4.点击下载的 ...

  4. IOS 如何持久化自定义对象 2014-08-01 01:38

    如果持久话自定义对象 那么这个对象一定要遵循 NSCoding 协议 并实现编解码:然后再将编解码后的数据 NSKeyedArchiver 到NSData中   @interface NSKeyAnd ...

  5. Markdown实验样例

    一级标题 二级标题 三级标题 重新开始一个段落 这是新的段落 斜体文本 粗体文本 粗斜体文本 下面是分隔线 删除线 下划线 脚注[1] 无序列表 第一项 嵌套元素1 嵌套元素2 第二项 嵌套元素1 嵌 ...

  6. ARM伪指令与伪操作

    一.伪指令 ARM伪指令有四个,分别是LDR.ADR.ADRL和NOP,下边对其分别介绍. 1.1 LDR LDR 伪指令用于加载 32 位的立即数或一个地址值到指定寄存器 .形式如  LDR{con ...

  7. windows操作报错:无法启动此程序,因为计算机中丢失api-ms-win-core-winrt-string-l1-1-0.dll

    在Windows上做提交svn操作时报错:无法启动此程序,因为计算机中丢失api-ms-win-core-winrt-string-l1-1-0.dll,如下图: 解决办法: 在 https://cn ...

  8. 基于函数的I/O操作(头文件stdio.h)

    基于函数库的I/O是C语言标准库的功能,基于系统级I/O函数实现. 系统级I/O函数对文件的标识是文件描述符,C语言标准库中对文件的标识是指向FILE结构的指针.在头文件cstdio或stdio.h中 ...

  9. 关于H标签 DL DT DD标签的一个小故事

    看了一篇关于SEO论坛的论文,大概故事内容是:一个专业的销售公司,里面SEO  技术多多,可就是销售网站的SEO的情况极为恼火.这天,老板又招到了一个SEO,直接聘为SEO主管全权负责网站的SEO,并 ...

  10. 系综的实现方式(nve、nvt、npt)

    一.NVE系综 更新位置和速度,v和e恒定. 二.NVT系综 几种实现的方式: 如: fix 1 all nve #更新位置和速度,e和V保持不变.若只有这个命令,就只nve系综,如果和控温命令一起, ...