Editorial for COCI '23 Contest 4 #5 Roboti
Submitting an official solution before solving the problem yourself is a bannable offence.
For , just answer
0
if or
and
-1
otherwise.
For ,
, for each query we can simulate a path in each direction from
and see if it
reaches
and count turns along the way. It might end up in an infinite loop; we can force it to stop
after
moves, because it's impossible for the distance to
to be that high.
For , we can imagine a graph where each pair of
and a direction is considered a vertex,
and there is an edge from one vertex to another if, after going from
in the direction given by the
initial vertex, our next move will be going from
of the next vertex in the direction given by the next
vertex. Notice that each vertex has outdegree
and outdegree
, so we have a graph which is a union of
cycles. Now we can easily see if
vertices are reachable from one another by checking if they're in the
same cycle, and also find the number of turns between them. We can do that for all
vertices that go out
of
and all
vertices that go into
and see which pair gives the smallest number of turns.
For the full solution, notice that, outside of the case where and row
doesn't have anything in
it or
and column
doesn't have anything in it, the only
that you need to make vertices
for are the
given
. With that, finding the minimum number of turns becomes quite easy, as every
vertex in the cycle represents one turn.
Comments