Need help in SPOJ AKBAR

This is the question from SPOJ. I have been trying this question for a day now. But it seems like I am not able to take care of the cycle in the graph and it is giving me WA. Can someone please help me out and tell me what am I doing wrong ?Here is the link to my submission