Codeforces Round 656 Div 3. Problem E

Hi Guys, I couldn’t solve question E of codeforces round 656 div 3 during the contest.

Link to problem :

So I thought to give it a try after reading the editorial. I have implemented recursive method of topological sorting before , so i tried to do it by iterative method, but somehow i couldn’t get the logic right .

This is the case on which my code fails
3 3
1 1 2
1 1 3
1 3 2

Here is the my code :

Can somebody help.

Found the iterative approach :