1. 程式人生 > >不光是查找值!"二分搜索"

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

inpu 情況下 scrip isdigit mine strong 們的 搜索 fin


從有序數組中查找某個值

  • 問題描述:給定長度為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 }
    最大化平均值

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