不光是查找值!"二分搜索"
从有序数组中查找某个值
- 问题描述:给定长度为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.39Sample 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 distanceSample Input
5 3
1
2
8
4
9Sample 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>=;
}最大化平均值
不光是查找值!"二分搜索"的更多相关文章
- 不光是查找值! "二分搜索"
2018-11-14 18:14:15 二分搜索法,是通过不断缩小解的可能存在范围,从而求得问题最优解的方法.在程序设计竞赛中,经常会看到二分搜索法和其他算法相结合的题目.接下来,给大家介绍几种经典的 ...
- Linux输入输出重定向和文件查找值grep命令
Linux输入输出重定向和文件查找值grep命令 一.文件描述符Linux 的shell命令,可以通过文件描述符来引用一些文件,通常使用到的文件描述符为0,1,2.Linux系统实际上有12个文件描述 ...
- 获取一个数组(vector)与查找值(value)的差最小绝对值的成员索引的算法
代码如下: 函数作用:传递进来一个数组(vector),和一个需要查找的值(value),返回与value的差值绝对值最小的vector成员索引,若value不在vector范围中,则返回-1: in ...
- Python3基础 setdefault() 根据键查找值,找不到键会添加
镇场诗: 诚听如来语,顿舍世间名与利.愿做地藏徒,广演是经阎浮提. 愿尽吾所学,成就一良心博客.愿诸后来人,重现智慧清净体.-------------------------------------- ...
- Python3基础 dict setdefault 根据键查找值,找不到键会添加
Python : 3.7.0 OS : Ubuntu 18.04.1 LTS IDE : PyCharm 2018.2.4 Conda ...
- java数组倒序查找值
java语言里面没有arr[:-2]这种方式取值 只能通过 arr[arr.length-1-x]的方式取值倒数的 x(标示具体的某个值)
- Excel-vlookup(查找值,区域范围,列序号,0)如何固定住列序列号,这样即使区域范围变动也不受影响
突然,发现VLOOKUP的列序列号并不会随着区域范围的改变而自动调节改变,只是傻瓜的一个数,导致V错值.所有,就想实现随表格自动变化的列序号. 方法一:在列序号那里,用函数得出永远想要的那个列在区域范 ...
- 9、Cocos2dx 3.0游戏开发三查找值小工厂方法模式和对象
重开发人员的劳动成果,转载的时候请务必注明出处:http://blog.csdn.net/haomengzhu/article/details/27704153 工厂方法模式 工厂方法是程序设计中一个 ...
- [Database] 不知道表名和字段查找值=1234的数据.
--如果表比较大,时间会比较长 DECLARE @searchValue NVARCHAR(50) SET @searchValue='1234' DECLARE @t TABLE ( rowNu ...
随机推荐
- Vuex mapGetter的基本使用
getter相当于Vuex中的计算属性 对 state 做处理再返回 mapGetters 把 Store 中的 getters 映射到组件中的计算属性中 Store文件 import Vue fro ...
- Homekit_人体感应器
前置需求: 苹果手机一台 Homekit人体感应一台 USB供电线一根 这款产品内置人体红外感应器,使用圆环设计,增大了其接触面积,使感应变得更加灵敏,重量轻,方便将其粘贴到墙上,同时支持二次开发,如 ...
- AndroidStudio新建项目报错build failed
AndroidStudio新建项目报错build failed 报错信息 org.gradle.initialization.ReportedException: org.gradle.interna ...
- Code Review 从失败中总结出来的几个经验
资深的程序员都知道 Code Review 可以对代码质量,代码规范,团队代码能力提升带来很大的提升,还有著名的技术专家"左耳朵耗子"也说过: 我认为没有 Code Review ...
- 国人开源了一款小而全的 Java 工具类库,厉害啊!!
最近栈长看到了一款小而全的 Java 工具类库:Hutool,Github 已经接近 14K Star 了,想必一定很优秀,现在推荐给大家,很多轮子不要再造了! Hutool 是什么 Hutool 是 ...
- Windows下nacos单机部分发现的坑
一.下载nacos的地址: https://github.com/alibaba/nacos/releases 下载 nacos-server-1.3.2.tar.gz 就好 二.在Window ...
- 笔记:html基础
一.HTML:超文本标记语言,是一种标签语言,不是编程语言,显示数据有双标签<body></body> 和单标签<img src=# / >, 标签大小写都可以 通 ...
- ganglia访问时出现"You don't have permission to access /ganglia/ on this server"
安装ganglia后,访问浏览器出现"You don't have permission to access /ganglia/ on this server" 按照网络上的要求配 ...
- 致敬学长!J20航模遥控器开源项目计划【开局篇】 | 先做一个开机界面 | MATLAB图像二值化 | Img2Lcd图片取模 | OLED显示图片
我们的开源宗旨:自由 协调 开放 合作 共享 拥抱开源,丰富国内开源生态,开展多人运动,欢迎加入我们哈~ 和一群志同道合的人,做自己所热爱的事! 项目开源地址:https://github.com/C ...
- magento2 定时任务
* * * * * /usr/bin/php /www/wwwroot/m2.demo.evebit.cn/bin/magento cron:run | grep -v "Ran jobs ...