How to solve CHAIN - Strange Food Chain spoj question.

//