洛谷 - 跳石头 (二分答案)

题目链接
题目:
在这里插入图片描述
在这里插入图片描述
二分答案,因为答案是具有单调性且有区间限制的,所以我们可以用二分来枚举答案解决,现在重要的如何去判断一个答案的有效性。我们只需要看看满足该要求的答案需要移掉多少石头就可以了

AC代码

#include <bits/stdc++.h>
inline long long read(){char c = getchar();long long x = 0,s = 1;
while(c < '0' || c > '9') {if(c == '-') s = -1;c = getchar();}
while(c >= '0' && c <= '9') {x = x*10 + c -'0';c = getchar();}
return x*s;}
using namespace std;
#define NewNode (TreeNode *)malloc(sizeof(TreeNode))
#define Mem(a,b) memset(a,b,sizeof(a))
#define lowbit(x) (x)&(-x)
const int N = 5e4 + 10;
const long long INFINF = 0x7f7f7f7f7f7f7f;
const int INF = 0x3f3f3f3f;
const double EPS = 1e-7;
const unsigned long long mod = 998244353;
const double II = acos(-1);
const double PP = (II*1.0)/(180.00);
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int,int> pii;
typedef pair<ll,ll> piil;
ll d,n,m,arr[N];
bool judge(ll Mid)//判断答案的有效性函数
{
    ll sum = 0,now = 0;
    ll l = 0,r = n+1;
    while(l < r)
    {
        l++;
        if(arr[l] - arr[now] < Mid)
            sum++;//移去的石头加一
        else
            now = l;//该石头不用移去
    }
    if(sum > m)
        return false;
    else
        return true;
}
int main()
{
    std::ios::sync_with_stdio(false);
    cin.tie(0),cout.tie(0);
    cin >> d >> n >> m;
    for(ll i = 1;i <= n;i++) cin >> arr[i];
    arr[n+1] = d;
    ll l = 1,r = d,ans = 0;
    while(l <= r)
    {
        ll Mid = (l+r)/2;
        if(judge(Mid))//判断
            ans = max(ans,Mid),l = Mid + 1;
        else
            r = Mid-1;
    }
    cout << ans << endl;
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值