二分搜索
直接上题:
https://www.acwing.com/problem/content/791/
直接看注释:
模板都在注释里
#include<iostream>
#define N 100010
using namespace std;
int a[N];
int n,q;
int main(){
cin>>n>>q;
for(int i=0;i<n;i++)
scanf("%d",a+i);
while(q--){
int x;
cin>>x;
int l=0,r=n-1;
// 先去找>=x的最左边的数
while(l<r){
int mid=l+r>>1;
if(a[mid]>=x) //若mid>=x,则要找的点一定在mid左边,或者就是mid,因此r=mid
r=mid;
else l=mid+1;
}
if(a[l]!=x){
cout<<"-1 -1"<<endl;
continue ;
}
cout<<l<<" ";
l=0,r=n-1;
while(l<r){
int mid=l+r+1 >>1;
if(a[mid]<=x) //若mid<=x,则要找的点一定在mid右边,或者就是mid,因此l=mid
l=mid;
else r=mid-1;
// 另外,如果是l=mid的话,需要mid=l+r+1>>1;
}
cout<<l<<endl;
}
}
非整数二分:
https://www.acwing.com/problem/content/792/
#include<iostream>
using namespace std;
#define EPS 1e-8
int main(){
double l=-10000,r=10000;
double n;
cin>>n;
while(r-l>=EPS){
double mid=(l+r)/2;
if(mid*mid*mid>n){
r=mid;
}else{
l=mid;
}
}
printf("%.6lf",l);
}