AcWing 730. 机器人跳跃问题(二分)

题目
一定要认真读题,读懂题的意思
本题是在上一个点e能量的基础上,进行能量的增减;公式:2*e-H(i)

运用二分的思想,来找答案,最后的 l 或 r 就是答案

#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>

using namespace std;

const int N = 100010;

int n;
int h[N];

bool check(int e)
{
    
    
    for (int i = 1; i <= n; i ++ )
    {
    
    
        e = e * 2 - h[i];
        if (e >= 1e5) return true;//此处不能省略,因为如果一直乘2,则会出现溢出现象,e可能超级大变为负值 
        if (e < 0) return false;
    }
    return true;
}

int main()
{
    
    
    scanf("%d", &n);
    for (int i = 1; i <= n; i ++ ) scanf("%d", &h[i]);

    int l = 0, r = 1e5;//设置高度的最小值和最大值 
    while (l < r)//对应二分的模板一 (AcWing 789. 数的范围) 
    {
    
    
        int mid = l + r >> 1;
        if (check(mid)) r = mid;
        else l = mid + 1;
    }

    printf("%d\n", l);//二分结束时  l=r

    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_47874905/article/details/114945960