Please help me in this .I m passing all sample test case yet facing WA. If there is any logical error can anyone help me out pls.

Thanks bro its worked but why i have to mod it externally in print statement .I have mod the ways variable once before print statement.

Because something like this is possible:

(8%5)(7%5) = 6 whereas the desired output was (8)(7)%5=1. So to make that happen we take the remainder one more time, so that 6%5 = 1.

Thanks man got it

I am getting TLE in this problem. 3.01 s. Here is my code Solution: 40702976 | CodeChef

Can anyone please help?

Your algorithm is not optimal to solve the problem. You are building matrix , I think you need to study adjacency list representation for graphs.

I am attaching my implementation for this problem . This will help you to understand the changes that you have to make. (my submission)

Thanks a lot ! Learnt something new!!