How to solve Siddharth and Permutations

how to solve this ques Siddharth and Permutations
https://hack.codingblocks.com/app/contests/course/c/212/p/347

my code https://ide.codingblocks.com/s/118241

i tried topological sort here but not able to proceed further . please somebody tell how to solve this