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:Online-Judge-Solutions/1024 - Permutations.cpp at master · marioyc/Online-Judge-Solutions · GitHub