help me arranging pairs

can anyone help me in arranging pairs in december long 2016 4th problem
Just a hint because in c I don’t think dynamic programming and vertual functions are not so easy.

Read the editorial after the contest is finished.

Well you were supposed to answer it.
But that’s okay I will try some other problem.

//