开发者

Efficiency problem

i am trying to make my algorithm more efficient but for som开发者_如何转开发e reason its not working correctly could someone tell me if my logic is correct. The general problem is that if u have a height of 'x', and you can jump 'u' distance but you fall 'd' distance if you havent cleared the height already. i have to calculate the number of jumps.

Initial code works correctly

while(x-u>0) {
    x=x-u+d;
    i++;
}
i++;

more efficient code (for some reason fails some cases, I don't know which cases though)

int k=u-d;
if(x-u<=0){
    i++;
} else {
    int z=x/k;
    if (x-((z-1)*k)-u <= 0) {
        i+=z;
    } else {
        i=i+z+1;
    }
}

let me try and clarify the problem you have a wall of height X, you can jump up distance U but every time you jump you also slip down distance D. so lets say if u have a wall of height x=4, u=4, d=1. Then you would only have to jump once because the first time you jump you have cleared the wall, so you dont slip down at all. now lets say x=6, u=4,d=1. Then you would have to jump twice because the first time you would jump up to 4 but fall 1 so you are at 3 then the next jump you clear the wall.


Okay, let's see. The last jump comes from the height of x - u or higher. The rest you have to cover in (u - d)-size steps, the number of such steps is of course (x - u)/(u - d).

After i-th step you are at height i * (u - d) + u (and falling down). So, in approx. (x - u)/(u - d) steps you are at height x - u + u = x. Recalling that the number of steps should be a whole number, we get the final result:

if (u >= x)
    return 1;
if (u <= d)
    throw "Impossible";
return ceil((x - u)/(u - d));

(ceil is a mathematical function returning the smallest integer not less than the given number.)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜