C++ robot jumping problem (binary search)

The robot is playing an old DOS-based game.
There are N+1 buildings in the game-numbered from 0 to N, arranged from left to right.
The height of the building numbered 0 is 0 units, and the height of the building numbered i is H(i) units.
At first, the robot was in the building numbered 0.
At each step, it jumps to the next (right) building.
Assuming that the robot is in the kth building, and its current energy value is E, it will jump to the k+1th building in the next step.
If H(k+1)>E, then the robot will lose the energy value of H(k+1)-E, otherwise it will get the energy value of EH(k+1).
The goal of the game is to reach the Nth building. In this process, the energy value cannot be a negative number of units.
The question now is how much energy should the robot start the game at least to guarantee the successful completion of the game?
Input format
Enter the integer N in the first line.
The second line is an integer separated by N spaces, H(1), H(2),...,H(N) represents the height of the building.
Output format
Output an integer, representing the result of rounding up the initial energy value of the minimum required unit.
Data range
1≤N, H(i)≤105,
input example 1:
5
3 4 3 2 4
output example 1:
4
input example 2:
3
4 4 4
output example 2:
4
input example 3:
3
1 6 4
Output sample 3:
3

AC code:

#include<stdio.h>
#include<algorithm>

using namespace std;

int n;
int h[100010];
int backup[100010];//数据备份
int ans=0x7f7f7f7f;

bool check(int e)
{
    
    
    long long int E=e;
    bool flag=true;
    for(int i=0;i<n;++i)
    {
    
    
        if(h[i+1]>E) E-=h[i+1]-E;
        else E+=E-h[i+1];
        if(E<0){
    
    flag=false;break;}
        //可以发现,每次E的新值都为2E-h[i+1]
        //当E>=最大柱子高度
        //E只增不降,不必再往下判断
        if(E>=backup[n]) break;
    }
    return flag;
}

int main()
{
    
    
    scanf("%d",&n);
    for(int i=1;i<=n;++i)
    {
    
    
        scanf("%d",&h[i]);
        backup[i]=h[i];
    }
    sort(backup+1,backup+n+1);//求最大柱子高度
    int l,r,mid;
    l=0;//左开右开区间
    r=backup[n]+1;
    while(l+1!=r)
    {
    
    
        mid=l+((r-l)>>1);
        if(check(mid)){
    
    //满足就继续探索更小的可能
            r=mid;
            ans=min(ans,mid);
        }
        else l=mid;//不满足只能往更大的去
    }
    printf("%d",ans);
    return 0;
}

Guess you like

Origin blog.csdn.net/qq_44643644/article/details/108806960