help needed in timus problem

http://acm.timus.ru/problem.aspx?space=1&num=1024
how to solve this efficiently,i did the bruteforce but then searched and in the code it was gcd and bfs type.
please explain
solution link:https://github.com/marioyc/Online-Judge-Solutions/blob/master/Timus%20Online%20Judge/1024%20-%20Permutations.cpp