不光是查找值!"二分搜索"
从有序数组中查找某个值
- 问题描述:给定长度为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 ...
随机推荐
- C#图解教程(第四版)—02—类的基本概念
类 是一种能 存储数据 并且 执行代码 的数据结构,他包含数据成员和函数成员 .成员可以是9种可能的成员类型的任意组合 字段 属性 方法 常量 构造函数 析构函数 运算符 索引器 事件 1 字 ...
- 跳转语句—break,continue,goto
#define _CRT_SECURE_NO_WARNINGS#include<stdio.h>#include<string.h>#include<stdlib.h&g ...
- 一个基于 Beego 的,能快速创建个人博客,cms 的系统
学习beego时候开发的一个博客系统,在持续完善,有不足之处,望大佬们多多体谅,并且指出.感谢! Go Blog 一个基于Beego的,能快速创建个人博客,cms 的系统 包含功能 查看 Go Blo ...
- 完了,这个硬件成精了,它竟然绕过了 CPU...
我们之前了解过了 Linux 的进程和线程.Linux 内存管理,那么下面我们就来认识一下 Linux 中的 I/O 管理. Linux 系统和其他 UNIX 系统一样,IO 管理比较直接和简洁.所有 ...
- SparkStreaming-DStream(Discretized Stream)
DStream(Discretized Stream)离散流 ◆ 和Spark基于RDD的概念很相似,Spark Streaming使用离散流 (discretized stream)作为抽象表示,叫 ...
- Bagging与随机森林(RF)算法原理总结
Bagging与随机森林算法原理总结 在集成学习原理小结中,我们学习到了两个流派,一个是Boosting,它的特点是各个弱学习器之间存在依赖和关系,另一个是Bagging,它的特点是各个弱学习器之间没 ...
- Java算法之根据二叉树不同遍历结果重建二叉树
二叉树的遍历方式一般包括前序遍历.中序遍历以及后序遍历: 前序遍历:根结点 | 左子树 | 右子树 中序遍历:左子树 | 根结点 | 右子树 后序遍历:左子树 | 右子树 | 根结点 二叉树遍历的性质 ...
- Thrift IDL基本语法
简言:介绍Thrift的IDL基本语法,初次使用或多或少的会有很有"坑"要踩,但是我们要遇山挖山,遇海填海,在学习的道路上坚定的走下去,方可日后吹牛B! IDL Thrift 采用 ...
- Chrome中实时查看.md文件
经常用Vim的朋友,在Vim中有一个Markdown语法高亮的插件,叫做:vim-markdown ,用起来还不错. 在Chrome中有一个实时预览Markdown效果的扩展,叫做:Markdown ...
- ARDUBOY游戏开发之路(一) 初识ARDUBOY
一.什么是ARDUBOY Arduboy是一个仅有信用卡大小的创造.分享游戏的开放平台.爱好者可以免费从Arduboy中选择一款经典的游戏,然后将游戏在目前最流行的arduino平台上编程.Ardub ...