从有序数组中查找某个值

  • 问题描述:给定长度为n的单调不下降数列a0,…,an-1和一个数k,求满足ai≥k条件的最小的i。不存在则输出n。
  • 限制条件:
    1≤n≤106
    0≤a0≤a1≤…≤an-1<109
    0≤k≤109
  • 分析:二分搜索。STL以lower_bound函数的形式实现了二分搜索。
  • 代码:

     1 #include <cstdio>
     2 #include <cctype>
     3 #include <algorithm>
     4 #define num s-'0'
     5
     6 using namespace std;
     7
     8 const int MAX_N=100000;
     9 const int INF=0x3f3f3f3f;
    10 int n,k;
    11 int a[MAX_N];
    12
    13 void read(int &x){
    14     char s;
    15     x=0;
    16     bool flag=0;
    17     while(!isdigit(s=getchar()))
    18         (s=='-')&&(flag=true);
    19     for(x=num;isdigit(s=getchar());x=x*10+num);
    20     (flag)&&(x=-x);
    21 }
    22
    23 void write(int x)
    24 {
    25     if(x<0)
    26     {
    27         putchar('-');
    28         x=-x;
    29     }
    30     if(x>9)
    31         write(x/10);
    32     putchar(x%10+'0');
    33 }
    34
    35 int search(int);
    36
    37 int main()
    38 {
    39     read(n);read(k);
    40     for (int i=0; i<n; i++) read(a[i]);
    41     int p = search(k);
    42     write(p);
    43     putchar('\n');
    44     write(lower_bound(a,a+n,k)-a);
    45     putchar('\n');
    46 }
    47
    48 int search(int k)
    49 {
    50     int l=-1, r=n-1;
    51     while (r-l>1)
    52     {
    53         int mid=(r+l)/2;
    54         if (a[mid]>=k) r=mid;
    55         else l=mid;
    56     }
    57     return r;
    58 }

    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)内被判断出来
  • 代码:

     1 #include <cstdio>
     2 #include <cctype>
     3 #include <algorithm>
     4 #include <cmath>
     5 #define num s-'0'
     6
     7 using namespace std;
     8
     9 const int MAX_N=100000;
    10 const int INF=100000;
    11 int n,k;
    12 double L[MAX_N];
    13
    14 void read(int &x){
    15     char s;
    16     x=0;
    17     bool flag=0;
    18     while(!isdigit(s=getchar()))
    19         (s=='-')&&(flag=true);
    20     for(x=num;isdigit(s=getchar());x=x*10+num);
    21     (flag)&&(x=-x);
    22 }
    23
    24 void write(int x)
    25 {
    26     if(x<0)
    27     {
    28         putchar('-');
    29         x=-x;
    30     }
    31     if(x>9)
    32         write(x/10);
    33     putchar(x%10+'0');
    34 }
    35
    36 double search();
    37 bool C(double x);
    38
    39 int main()
    40 {
    41     read(n);read(k);
    42     for (int i=0; i<n; i++) scanf("%lf", &L[i]);
    43     double p = search();
    44     printf("%.2f", floor(p*100)/100);
    45     putchar('\n');
    46 }
    47
    48 bool C(double x)
    49 {
    50     int sum=0;
    51     for (int i=0; i<n; i++)
    52     {
    53         sum+=(int)(L[i]/x);
    54         if (sum>=k) return true;
    55     }
    56     return false;
    57 }
    58
    59 double search()
    60 {
    61     double lb=0, ub=INF;
    62     //while (ub-lb>0.001)
    63     for (int i=0; i<100; i++)
    64     {
    65         double mid=(lb+ub)/2;
    66         if (C(mid)) lb=mid;
    67         else ub=mid;
    68     }
    69     return ub;
    70 } 

    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,这个问题的判断使用贪心法就可以解决。
  • 代码:

     1 #include <cstdio>
     2 #include <cctype>
     3 #include <algorithm>
     4 #include <cmath>
     5 #define num s-'0'
     6
     7 using namespace std;
     8
     9 const int MAX_N=101000;
    10 const int INF=0x3f3f3f3f;
    11 int N,M;
    12 int x[MAX_N];
    13
    14 void read(int &x){
    15     char s;
    16     x=0;
    17     bool flag=0;
    18     while(!isdigit(s=getchar()))
    19         (s=='-')&&(flag=true);
    20     for(x=num;isdigit(s=getchar());x=x*10+num);
    21     (flag)&&(x=-x);
    22 }
    23
    24 void write(int x)
    25 {
    26     if(x<0)
    27     {
    28         putchar('-');
    29         x=-x;
    30     }
    31     if(x>9)
    32         write(x/10);
    33     putchar(x%10+'0');
    34 }
    35
    36 bool C(int);
    37
    38 int main()
    39 {
    40     read(N);read(M);
    41     for (int i=0; i<N; i++) read(x[i]);
    42     sort(x, x+N);
    43     int lb=0, ub=INF;
    44     while (ub-lb>1)
    45     {
    46         int mid=(lb+ub)/2;
    47         if (C(mid)) lb=mid;
    48         else ub=mid;
    49     }
    50     write(lb);
    51     putchar('\n');
    52 }
    53
    54 bool C(int d)
    55 {
    56     int last=0;
    57     for (int i=1; i<M; i++)
    58     {
    59         int crt=last+1;
    60         while (crt<N && x[crt]-x[last]<d) crt++;
    61         if (crt==N) return false;
    62         last=crt;
    63     }
    64     return true;
    65 }

    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)
  • 代码:

     1 #include <cstdio>
     2 #include <cctype>
     3 #include <algorithm>
     4 #include <cmath>
     5 #define num s-'0'
     6
     7 using namespace std;
     8
     9 const int MAX_N=101000;
    10 const int INF=0x3f3f3f3f;
    11 int n,k;
    12 int v[MAX_N],w[MAX_N];
    13 double y[MAX_N];
    14
    15 void read(int &x){
    16     char s;
    17     x=0;
    18     bool flag=0;
    19     while(!isdigit(s=getchar()))
    20         (s=='-')&&(flag=true);
    21     for(x=num;isdigit(s=getchar());x=x*10+num);
    22     (flag)&&(x=-x);
    23 }
    24
    25 void write(int x)
    26 {
    27     if(x<0)
    28     {
    29         putchar('-');
    30         x=-x;
    31     }
    32     if(x>9)
    33         write(x/10);
    34     putchar(x%10+'0');
    35 }
    36
    37 bool C(double);
    38
    39 int main()
    40 {
    41     read(n);read(k);
    42     for (int i=0; i<n; i++)
    43     {
    44         read(w[i]);
    45         read(v[i]);
    46     }
    47     double lb=0, ub=INF;
    48     for (int i=0; i<100; i++)
    49     {
    50         double mid=(lb+ub)/2;
    51         if (C(mid)) lb=mid;
    52         else ub=mid;
    53     }
    54     printf("%.2f\n",ub);
    55 }
    56
    57 bool C(double x)
    58 {
    59     for (int i=0; i<n; i++)
    60     {
    61         y[i]=v[i]-x*w[i];
    62     }
    63     sort(y,y+n);
    64     double sum=0;
    65     for (int i=0; i<k; i++)
    66     {
    67         sum+=y[n-1-i];
    68     }
    69     return sum>=0;
    70 }

    最大化平均值

转载于:https://www.cnblogs.com/Ymir-TaoMee/p/9492747.html

不光是查找值!二分搜索相关推荐

  1. excel查找出不来了_Excel查找值不唯一,一个VLOOKUP公式拖拉出多个结果啦

    今天介绍VLOOKUP函数查询"一对多",也就是VLOOKUP查找值有重复,需要返回多个结果. VLOOKUP语法 "=VLOOKUP(查找值,数据表,序列数,[匹配条件 ...

  2. python检索用人名查电话_创建一个将人名用作键的字典后,输入姓名查找值,返回错误...

    创建了将人名用作键的字典,输入姓名查找值,返回错误. 代码: people={ 'Alice': { 'phone': '6789', 'addr': 'Ruan road 23' }, 'Mary' ...

  3. python人名查电话(字典)_python检索用人名查电话_创建一个将人名用作键的字典后,输入姓名查找值,返回错误......

    创建了将人名用作键的字典,输入姓名查找值,返回错误. 代码: people={ 'Alice': { 'phone': '6789', 'addr': 'Ruan road 23' }, 'Mary' ...

  4. 数据结构:二叉树的创建,打印前中后序遍历,节点个数,叶子节点数,销毁,第K层中节点的个数,查找值为x的节点

    二叉树遍历:按照某种特定的规则,依次对二叉树中的节点进行相应的操作,并且每个节点只操作一次.(采用递归思想) 先序遍历:先遍历根节点,再遍历根节点的左子树,最后遍历根节点的右子树. 中序遍历:先遍历左 ...

  5. python从键盘输入一个列表计算输出元素的平均值_python列表查找值_在Python中查找列表平均值的5种方法...

    python列表查找值 Hi Folks! In this article, we will have a look at the various ways to find the average o ...

  6. Excel VLOOKUP实用教程之 03 使用下拉列表作为查找值vlookup?(教程含数据excel)

    实战需求 vlookup如何双向查找,两个字段查询数据? 文章目录 <示例 1 – 查找 Brad 的数学分数> <示例 2 – 双向查找> <示例 3 – 使用下拉列表 ...

  7. 玩转算法面试-第四章查找值之leetcod相关笔记

    查找问题 4-1,2 两类查找问题 1 查找有无:set 2 查找对应关系:map 常见的四种操作: insert, find, erase, change(map) 例题 leetcode 349 ...

  8. js实现二分查找(二分搜索)

    首先了解什么是数据结构和算法 数据结构 = 数据结构 + 算法 数据结构:用来存储数据的数组 算法:暴力搜索,二分搜索 二分搜索:是一个搜索某个值的索引的算法 条件:在一个有序的数组中查找一个特定的元 ...

  9. 关于二分查找和二分搜索

    首先是二分查找,举个有序的整数数组例子(二分查找和搜索都是针对有序数组) public int rank(int key, int n) {int lo = 0, hi = n - 1;while ( ...

最新文章

  1. excel:替换问号?时会所有数据被替换掉(通配符问题)
  2. C/C++函数形参传实参时值传递、指针传递、引用传递的区别
  3. 如何在ASP.NET中使用Windows Live Web Bar
  4. DFTug - Getting Started(下篇)
  5. ORA-12541:TNS没有监听器
  6. Python中lambda表达式的优缺点及使用场景
  7. 如何让apache支持.htaccess 解决Internal Server Error The server …错误
  8. 学习笔记day5:inline inline-block block区别
  9. 算法 - 二分查找(非递归实现二分查找)
  10. 利用cors,实现js跨域访问Tomcat下资源
  11. linux wkhtmltopdf换字体,ubuntu – 更新后Wkhtmltopdf字体大小增加
  12. 提取点位属性文本_手把手教你如何用Python爬取网站文本信息
  13. 英语总结系列(二十一):英语也能玩出新花样
  14. jQuery LigerUI 初次发布一睹为快(提供Demo下载)
  15. sticky-footer布局
  16. vue日历插件vue-calendar
  17. 中国指定银行支行数据及省市数据获取
  18. 检测卡常见错误:1A、1B、20、21、22
  19. rgb sw 线主板接口在哪_有颜值也有实力!利民TL-C12S幻彩RGB电脑散热风扇评测
  20. html中header怎么设置,HTML中的header标签怎么用?

热门文章

  1. 通过hsv筛选颜色 python_OpenCV-Python 光流介绍(附代码)
  2. plsql developer无监听程序_252百战程序员022天
  3. Python入门--while循环
  4. php算法不大于n的质数,php求不大于n的质数
  5. [leetcode] 7. 整数反转
  6. Unity3D之NGUI基础7:UI动态加载
  7. C#基础4:函数+ref和out参数
  8. bzoj 2216: [Poi2011]Lightning Conductor(DP决策单调性)
  9. matlab 纹理映射
  10. 01背包问题笔记(转载)