gawkmaster069's blog

By gawkmaster069, history, 6 months ago, In English

What is Greedy?

A greedy algorithm is a simple strategy where, at every step, you choose the option that looks the best at that moment. You don’t worry about future consequences or long-term planning. You simply pick the move that gives the maximum immediate benefit. The idea is that by always taking the locally best choice, you aim to reach an overall good or optimal solution during your loop process.

A Newbie Problem Example.

Super Mario Problem

t = int(input())
for _ in range(t):
    a, b, k = map(int, input().split())
    
    total = a * b
    rows = a
    cols = b
    moves = 0
    
    while total > k:
        if b >= a and rows > 0:
            total -= b
            rows -= 1
        else:
            total -= a
            cols -= 1
        moves += 1
    
    print(moves)

Above is the solution for the given problem , explanation below.

In the above given problem you don't think much , you keep reducing the rows and column until m*n falls below k which is condition for the army retreatment, however sometimes removing a row might give more advantage than removing a column so for that you check each row and column value too before removing and keep the loop on till it reaches the value k.

How to spot a greedy problem?

You can easily spot such greedy problems by seeing if the numbers or the given numbers needs to be changed in the process and a condition being linked to that, these type of questions always follow greedy approach however there might be much more complex greedy problems much more deeper than the above stated one but this is fine for a good start.

Open for suggestions in the comments.

Full text and comments »

  • Vote: I like it
  • -99
  • Vote: I do not like it