一、思路
(1)mid=(l+r+1)/2
????????if(check(mid)):1.true? ? ? [mid,r]? ? ? ?l=mid
? ? ? ? ? ????????? ? ? ? ? ? ?2.false? ? ?[l,mid-1]? ? r=mid-1
(2)mid=(l+r)/2
????????if(check(mid)):1.true? ? ? [l,mid]? ? ? ? r=mid
? ? ? ? ?? ? ? ? ? ? ? ? ? ? ? 2.false? ? ?[mid+1,r]? ?l=mid+1
二、模板
如何選擇模板?
根據check函數選擇
數的范圍
#include<bits/stdc++.h>
using namespace std;const int N=1e5+10;int n,m,x;
int q[N];int main()
{scanf("%d%d",&n,&m);for(int i=0;i<n;i++)scanf("%d",&q[i]);while(m--){int x; scanf("%d",&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<<l<<endl;}}return 0;
}
數的三次方根
#include<bits/stdc++.h>
using namespace std;const int N=1e5+10;
int q[N];
double n;int main()
{scanf("%lf",&n);double l=-1000,r=1000;while(r-l>=1e-7){double mid=(l+r)/2;if(mid*mid*mid<=n)l=mid;else r=mid;}printf("%.6lf%",l);return 0;
}