二分答案与二分查找模板又有些许不同

[二分答案] [c++]
1
2
3
4
5
6
7
8
9
10
11
12
while(l<=r)//此处是小于等于
{
mid=(l+r)>>1;
if(check(mid))
{
ans =mid;
l=mid+1
}
else r=mid-1;
}


洛谷P2678 跳石头
当一道题目直接求解答案会很困难,但是根据题意去验证答案会很简单,那么我们就利用逆向思维,直接枚举答案,利用刚刚学到的二分查找去查找答案,然后去直接按照题意验证答案,验证成功即可输出,所以二分更多的就是逆向思维

[跳石头] [c++]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#include <bits/stdc++.h>
using namespace std;
const int N=1e5+7;
int a[N],ans;
bool check(int x,int b[],int n,int m)
{
int now=0,tot=0;
for(int j=1;j<=n+1;j++)
{
if(a[j]-a[now]<x) tot++;//如果距离小 这颗石头可以搬走
else
{
now=j;// 如果距离大,就跳过去
}
}
if(tot>m) return false;
else return true;
}

int main()
{
int L,n,m;
cin>>L>>n>>m;
for(int i=1;i<=n;i++) cin>>a[i];
a[n+1]=L;
int l=1,r=L;
while(l<=r)
{
int mid=(l+r)>>1;
if (check(mid,a,n,m))
{
ans=mid;
l=mid+1;//如果搬的石头少 最短跳跃距离可能可以更大
}
else r=mid-1;
}
cout<<ans<<endl;
}