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



从有序数组中查找某个值

  • 问题描述:给定长度为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

时间: 2024-07-31 16:16:16

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

不光是查找值! &quot;二分搜索&quot;

2018-11-14 18:14:15 二分搜索法,是通过不断缩小解的可能存在范围,从而求得问题最优解的方法.在程序设计竞赛中,经常会看到二分搜索法和其他算法相结合的题目.接下来,给大家介绍几种经典的二分搜索法的问题. 一.从有序数组中查找某个值 1.lowerBound 问题描述: 给定长度为n的单调不下降数列a和一个数k,求满足ai >= k条件的最小的i.不存在的情况下输出n. 限制条件: 1 <= n <= 10 ^ 6 0 <= ai < 10 ^ 9 0 <

(一)Python入门-3序列:18字典-核心底层原理-内存分析-查找值对象过程

一:根据键查找“键值对”的底层过程 明白一个键值对是如何存储到数组中的,根据键对象取到值对象,理解起来就 简单了. >>> a.get("name") 'jack' 当我们调用a.get(“name”),就是根据键“name”查找到“键值对”,从而找到值对象“jack”. 第一步,我们仍然要计算“name”对象的散列值: >>> bin(hash("name")) '-0b10101111010011101101011001001

循环有序数组,查找值

一.从一个循环有序数组总查找给定值 1.思路:先通过中间值和最后一个或者第一个元素比较,找出局部有序范围,再通过二分查找局部有序段 private static int sortArrFindOne(int arr[], int low, int high, int target) { int mid = (high - low) / 2 + low; if (arr[mid] == target) return mid; if (arr[mid] < arr[high]) { if (arr[

二叉查找树(3) - 查找值最小的节点

查找最小值的操作是很简单的,只需要从根节点递归的遍历到左子树节点即可.当遍历到节点的左孩子为NULL时,则这个节点就是树的最小值. 上面的树中, 从根节点20开始,递归遍历左子树,直到为NULL.因为节点4的左子树为NULL,则4就是树的最小值. 代码实现查找最小值: Node * minValueNode(Node* node) { Node* current = node; //查找最左侧的叶子 while (current->left != NULL) current = current-

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

镇场诗: 诚听如来语,顿舍世间名与利.愿做地藏徒,广演是经阎浮提. 愿尽吾所学,成就一良心博客.愿诸后来人,重现智慧清净体.------------------------------------------ code: dict1={'子':'鼠','丑':'牛','寅':'虎','卯':'兔','辰':'龙','巳':'蛇','午':'马','未':'羊','申':'猴','酉':'鸡','戌':'狗','亥':'猪'} #找得到返回 print(dict1.setdefault('子'))

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

? python : 3.7.0 OS : Ubuntu 18.04.1 LTS IDE : PyCharm 2018.2.4 conda : 4.5.11 type setting : Markdown ? code """ @Author : 行初心 @Date : 18-9-23 @Blog : www.cnblogs.com/xingchuxin @GitHub : github.com/GratefulHeartCoder """ de

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

突然,发现VLOOKUP的列序列号并不会随着区域范围的改变而自动调节改变,只是傻瓜的一个数,导致V错值.所有,就想实现随表格自动变化的列序号. 方法一:在列序号那里,用函数得出永远想要的那个列在区域范围中的列数:区域范围内的目标列COLUMN值-区域范围首列COLUMN值+1 =VLOOKUP(I2,$B$2:$G$15,COLUMN($G$2)-COLUMN($B$2)+1,0) 方法二: 原文地址:https://www.cnblogs.com/Formulate0303/p/1104544

查找算法——————二分搜索

最常见的判断是存在key,如果存在输出位置,否则输出-1. int BinSearch(int l,int r,int key){ //judge exist int md; while(l <= r){ md= (l+r)/2; if(key < a[md]){ r = md - 1; }else if(key > a[md]){ l = md + 1; }else{ return md; } } return -1; //no exist } 如果要求是大于等于key的最小位置时.只

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

重开发人员的劳动成果,转载的时候请务必注明出处:http://blog.csdn.net/haomengzhu/article/details/27704153 工厂方法模式 工厂方法是程序设计中一个经典的设计模式.指的是基类中仅仅定义创建对象的接口,将实际的实现推迟到子类中. 在这里.我们将它稍加推广,泛指一切生成并返回一个对象的静态函数. 一个经典的工厂方法如同这样: Sprite* factoryMethod() { Sprite* ret = new Sprite(); //在这里对 r