博客
关于我
二分法模板
阅读量:734 次
发布时间:2019-03-21

本文共 654 字,大约阅读时间需要 2 分钟。

二分法模板

二分的核心思想是解决边界问题。对于整数的边界,我们通常会在计算时加一再减一,这样可以避免直接取到边界值导致的死循环问题。不过,对于浮点数来说,这种处理就不需要,因为直接除以2已经可以得到中间值了。

整数二分法

整数二分法通常分为三个部分:判定函数、查找函数以及主函数。

定义判定函数bool judge(int mid) {int a = ...;if (满足题意条件) {return true;} else {return false;}}

主函数int solve1() {int l, r, mid;// 根据题目定义初始值while (条件不满足) {mid = (l + r) / 2;if (judge(mid)) {l = mid + 1;} else {r = mid;}}}

浮点数二分法

双变量solve1() {double l, r, mid;// 根据题目定义初始值while (r - l > eps) {mid = (l + r) / 2;if (judge(mid)) {l = mid + eps;} else {r = mid - eps;}}return r;}

双变量solve2() {double l, r, mid;// 根据题目定义初始值while (r - l > eps) {mid = (l + r) / 2;if (judge(mid)) {r = mid - eps;} else {l = mid + eps;}}return r;}

转载地址:http://rtagz.baihongyu.com/

你可能感兴趣的文章
Python: AES加密与解密
查看>>
Python: Range() 最大尺寸;动态的还是静态的?
查看>>
Python: Windows下用 multiprocessing 的深坑
查看>>
python:Could not find platform independent libraries <prefix>解决方法
查看>>
Python:datetime tzinfo 时区名称文档
查看>>
Python:deepcopy(list) vs new_list = old_list[:]
查看>>
Python:Google API - 从消息中获取 mimeTypes
查看>>
Python:Google API - 从消息中获取 mimeTypes
查看>>
Python:subprocess.call,stdout to file,stderr to file,在屏幕上实时显示stderr
查看>>
Python:TypeError:无法连接“str“和“int“对象
查看>>
Python:XPath 在 ElementTree 中不可用
查看>>
Python:从 FTP 服务器下载文件
查看>>
python:从列表中创建元组列表
查看>>
Python:从嵌套列表中删除重复项
查看>>
Python:从间隔映射到值
查看>>
Python:使用 shell=False 的子进程调用不起作用
查看>>
Python:修改 PATH 环境变量的平台无关方式
查看>>
Python:假与 0
查看>>
Python:函数使用
查看>>
Python:函数进阶
查看>>