How to spot a “greedy” algorithm?

前端 未结 3 1675
独厮守ぢ
独厮守ぢ 2021-01-31 19:36

I am reading a tutorial about \"greedy\" algorithms but I have a hard time spotting them solving real \"Top Coder\" problems.

If I know that a given problem can

3条回答
  •  野性不改
    2021-01-31 20:28

    Formally, you'd have to prove the matroid property of course. However, I assume that in terms of topcoder you rather want to find out quickly if a problem can be approached greedily or not.

    In that case, the most important point is the optimal sub-structure property. For this, you have to be able to spot that the problem can be decomposed into sub-problems and that their optimal solution is part of the optimal solution of the whole problem.

    Of course, greedy problems come in such a wide variety that it's next to impossible to offer a general correct answer to your question. My best advice would hence be to think somewhere along these lines:

    • Do I have a choice between different alternatives at some point?
    • Does this choice result in sub-problems that can be solved individually?
    • Will I be able to use the solution of the sub-problem to derive a solution for the overall problem?

    Together with loads and loads of experience (just had to say that, too) this should help you to quickly spot greedy problems. Of course, you may eventually classify a problem as greedy, which is not. In that case, you can only hope to realize it before working on the code for too long.

    (Again, for reference, I assume a topcoder context.. for anything more realistic and of practical consequence I strongly advise to actually verify the matroid structure before selecting a greedy algorithm.)

提交回复
热议问题