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 : https://codeforces.com/contest/1385/problem/E

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 : https://codeforces.com/contest/1385/submission/87232399

Can somebody help.

Found the iterative approach : https://codeforces.com/contest/1385/submission/87239702