Theseus and labyrinth

CodeForces - 676D