ELEVTRBL - Elevator Trouble

You are on your way to your first job interview as a program tester, and you are already late. The interview is in a skyscraper and you are currently in floor s, where you see an elevator. Upon entering the elevator, you learn that it has only two buttons, marked "UP u" and "DOWN d". You conclude that the UP-button takes the elevator u floors up (if there aren't enough floors, pressing the UP-button does nothing, or at least so you assume), whereas the DOWN-button takes you d stories down (or none if there aren't enough). Knowing that the interview is at floor g, and that there are only f floors in the building, you quickly decide to write a program that gives you the amount of button pushes you need to perform. If you simply cannot reach the correct floor, your program halts with the message "use the stairs".

Given input f, s, g, u and d (floors, start, goal, up, down), find the shortest sequence of button presses you must press in order to get from s to g, given a building of floors, or output "use the stairs" if you cannot get from s to g by the given elevator.


The input will consist of one line, namely f s g u d, where 1 <= s, g <= f <= 1000000 and 0 <= u, d <= 1000000. The floors are one-indexed, i.e. if there are 10 stories, s and g be in [1; 10].


You must reply with the minimum numbers of pushes you must make in order to get from s to g, or output "use the stairs" if it is impossible given the conguration of the elevator.


10 1 10 2 1

100 2 1 1 0 

use the stairs

hide comments
veerendrasd_9: 2019-07-23 17:54:33

remember to define a tree such that a property can do the work, in such type of problems.

prudhvi_495: 2019-06-20 12:03:02

It's a simple bfs problem just print the level of g in the graph.

cenation007: 2019-06-03 07:28:15

bfs is love

dkkv0000: 2019-05-25 07:15:59

good bfs

dmorgans: 2019-04-12 20:36:21

ac in 2nd attempt
test case 11 is good one...

dashubaba: 2019-04-12 18:56:21

Dear admin, can you give me some clue where I got the WA.

mynk322: 2019-03-12 20:03:07

AC in 2nd go!
Got TLE the first time...
After thinking for a few minutes, thought of a change applied it and BOOM!
got an AC!!!

vickyand_27: 2019-01-31 17:04:41

my 14th bfs is cool

harshraj22aug: 2018-12-19 17:31:40

what is the problem if we mark the floor as reached when we pop it out of the queue instead of marking it while pushing in ?

Last edit: 2018-12-19 17:32:30
surajkumar_cse: 2018-12-14 11:45:57

I was getting TLE in my first attempt. Everything was correct.
then I got a slight hint that:
i was making that floor visited after popping it out of the queue.

So I corrected it and make visited as soon as I push that floor in to the queue. AC

I hope this mistake will save my time in further questions.

Added by:Krzysztof Lewko
Time limit:1s
Source limit:50000B
Memory limit:1536MB
Cluster: Cube (Intel G860)
Languages:All except: ASM64
Resource:Nordic programming contest