henar, the bug in your program is in your choose function where you have *n_nodes--; it should be (*n_nodes)--;
But now your program has the same problem as mine: it is too slow to pass the judging. There must be a better algorithm, but does anyone know what it is?