代码如下
/数的范围/
#include<bits/stdc++.h>
using namespace std;
const int N=1e5+5;
int n,m,q[N];
int main(){
cin>>n>>m;
for(int i=0;i<n;i++){
cin>>q[i];
}
while(m--){
int x;
cin>>x;
int l=0,r=n-1;
while(l<r)//先找左端点
{
int mid=l+r>>1;
if(q[mid]>=x)r=mid;
else l=mid+1;
}
if(q[l]!=x)cout<<"-1 -1"<<endl;//如果不存在直接输出
else{//寻找右端点
cout<<l<<' ';
int l=0,r=n-1;
while(l<r)
{
int mid=l+r+1>>1;//防止成负数
if(q[mid]<=x)l=mid;
else r=mid-1;
}
cout<<r<<endl;
}
}
return 0;
}
/数的立方根/
#include<bits/stdc++.h>
using namespace std;
int main(){
double x;
cin>>x;
double l=-100,r=100;
while(r-l>1e-8)//逆推法
{
double mid=(l+r)/2;
if(mid*mid*mid>=x)r=mid;
else l=mid;
}
printf("%.6lf\n",l);
return 0;
}
数的范围的思想:将l与r看作未知数,在长度为n的数组中,用二分的思想更新l的位置,直到l>r;
r的位置同理。
数的立方根的思想:将二分结果不断带入验证更新。