HELP in Rank Fraud(RANKFRAD)

This is the question:
I tried solving it but couldn’t. My approach was to find a path that visits each vertex once(hamiltonian path). However, the solution is in O(N^2) time. I tried looking at some solutions but could not understand them. For example: this one
However, I couldn’t understand the sort function and why does it work. Could someone help me. Thanks in advance.