博客
关于我
二分法模板
阅读量: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/

你可能感兴趣的文章
org.apache.dubbo.common.serialize.SerializationException: com.alibaba.fastjson2.JSONException: not s
查看>>
sqlserver学习笔记(三)—— 为数据库添加新的用户
查看>>
org.apache.http.conn.HttpHostConnectException: Connection to refused
查看>>
org.apache.ibatis.binding.BindingException: Invalid bound statement错误一例
查看>>
org.apache.ibatis.exceptions.PersistenceException:
查看>>
org.apache.ibatis.exceptions.TooManyResultsException: Expected one result (or null) to be returned
查看>>
org.apache.ibatis.type.TypeException: Could not resolve type alias 'xxxx'异常
查看>>
org.apache.poi.hssf.util.Region
查看>>
org.apache.xmlbeans.XmlOptions.setEntityExpansionLimit(I)Lorg/apache/xmlbeans/XmlOptions;
查看>>
org.apache.zookeeper.KeeperException$ConnectionLossException: KeeperErrorCode = ConnectionLoss for /
查看>>
org.hibernate.HibernateException: Unable to get the default Bean Validation factory
查看>>
org.hibernate.ObjectNotFoundException: No row with the given identifier exists:
查看>>
org.springframework.beans.factory.BeanDefinitionStoreException
查看>>
org.springframework.boot:spring boot maven plugin丢失---SpringCloud Alibaba_若依微服务框架改造_--工作笔记012
查看>>
SQL-CLR 类型映射 (LINQ to SQL)
查看>>
org.springframework.orm.hibernate3.support.OpenSessionInViewFilter
查看>>
org.springframework.orm.hibernate3.support.OpenSessionInViewFilter
查看>>
org.springframework.web.multipart.MaxUploadSizeExceededException: Maximum upload size exceeded
查看>>
org.tinygroup.serviceprocessor-服务处理器
查看>>
org/eclipse/jetty/server/Connector : Unsupported major.minor version 52.0
查看>>