Python – Platforms Jumping – CodeForces

Greedy algorithm is described as an algorithm that follows the problem-solving heuristic of making the locally optimal choice at each stage with the intent of finding a global optimum. Thus, it is always interesting to find a problem, which can be solved with a greedy algorithm – mainly because one does not need an advanced data structure or data structure of data structures for it. The codeforces problem Platform Jumping could be solved with a greedy algorithm quite nicely.

The problem could be defined in short like this:

You stay on a river with a given width. There are given numbers of with different size platforms, which could be moved before the jump without changing their initial order. The max length of jump is given as well. The output is consisting of printing YES, if it is possible to cross the river and a position of the platforms, as they are put in order to facilitate the passing. The position of the platforms is printed as their sequential number. E.g., on the picture below, the output should look like this:

The solution looks like “Greedy” could be implemented in the following way – put the platforms exactly in such a way, that they facilitate the maximum jump. If it is possible to reach the opposite bank of the river – then there is a solution. In the code, the decision, whether there is a possible solution is taken in the following lines:

Once there is a way to pass through, the greedy algorithm continues – it says that all the jumps should be of equal size, but 1. Thus, it will be easy to print the solution.

Once the number of jumps and their size is known, “feeding” the data into a list is quite straight forward, writing “0” for the “water” and platform_counter  for the consecutive platform units:

The whole solution is present here:

That’s all folks!

Tagged with: , , ,