ACM寒假集训#3

二分查找

二分查找也称折半查找(Binary Search),它是一种效率较高的查找方法。但是,折半查找要求线性表必须采用顺序存储结构,而且表中元素按关键字有序排列。

首先,假设表中元素是按升序排列,将表中间位置记录的关键字与查找关键字比较,如果两者相等,则查找成功;否则利用中间位置记录将表分成前、后两个子表,如果中间位置记录的关键字大于查找关键字,则进一步查找前一子表,否则进一步查找后一子表。重复以上过程,直到找到满足条件的记录,使查找成功,或直到子表不存在为止,此时查找不成功。

算法复杂度

二分查找的基本思想是将n个元素分成大致相等的两部分,取a[n/2]与x做比较,如果x=a[n/2],则找到x,算法中止;如果x<a[n/2],则只要在数组a的左半部分继续搜索x,如果x>a[n/2],则只要在数组a的右半部搜索x.
时间复杂度即是while循环的次数。
总共有n个元素,
渐渐跟下去就是n,n/2,n/4,…n/2^k(接下来操作元素的剩余个数),其中k就是循环的次数
由于你n/2^k取整后>=1
即令n/2^k=1
可得k=log2n,(是以2为底,n的对数)
所以时间复杂度可以表示O(h)=O(log2n)

代码示例

int find(){
	int left=0,right=n;//设置左右边界	
	while(right>=left){
		int mid=(right+left)/2;//二分中值
		if(mid==target)return mid;
		else if(target>mid)left=mid+1;//若目标大于中值,则调整左边界
		else if(target<mid)right=mid-1;//若目标小于中值,则调整右边界
	}
	return -1;
}

题目示例

Now,given the equation 8x^4 + 7x^3 + 2x^2 + 3x + 6 == Y,can you find its solution between 0 and 100;
Now please try your lucky.

input

The first line of the input contains an integer T(1<=T<=100) which means the number of test cases. Then T lines follow, each line has a real number Y (fabs(Y) <= 1e10);

output

For each test case, you should just output one real number(accurate up to 4 decimal places),which is the solution of the equation,or “No solution!”,if there is no solution for the equation between 0 and 100.

Sample Input

2
100
-4

Sample Output

1.6152
No solution!

代码示例

#include<iostream>  
#include<stdio.h>   
#include<algorithm> 
#include<cmath>     
using namespace std;
double solve(double x){
	return 8*pow(x,4)+7*pow(x,3)+2*pow(x,2)+3*x+6;//返回计算值
}
double find(double y,double l,double r){//二分查找
	double m=(l+r)/2;
	if(r-l>=10e-7){//设置精确值
		if(solve(m)==y)return m;
		else if(solve(m)>y)return find(y,l,m);//迭代函数查找
		else return find(y,m,r);
	}
	return m;
}
int main(){//主函数
	int T;
	cin>>T;
	while(T--){
		double l=0,r=100,y;
		cin>>y;
		if(y<solve(1)||y>solve(100))cout<<"No solution!"<<endl;
		else printf("%0.4lf\n",find(y,0,100));//通过引用函数直接得到答案
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值