Editorial for COCI '21 Contest 2 #2 Kutije


Remember to use this editorial only when stuck, and not to copy-paste code from it. Please be respectful to the problem author and editorialist.
Submitting an official solution before solving the problem yourself is a bannable offence.

For the second subtask, it is sufficient to go through all of the meetups and pairs of meetups, and for each possibility, determine in which box the toy in question will end up in and check if this is the desired box.

In the third subtask, for each question, we can recursively determine in which boxes the staring toy can end up in. If we are currently at some box, we can go through all friends, check where would the toy end up after a meeting with that friend and then make a recursive call in case we haven't already visited that box. In the end, we check if the toy has ever visited the desired box.

For the first subtask, for each toy, we can do the following: we determine in which box it ends up in after one meetup, then after two meetups, then three, and so on, until we return to the starting box. Then we know that the boxes in the meetups will repeat periodically after that. So, it is sufficient to store for each toy all of the boxes it can end up in, and then we can answer the questions.

For the whole solution, the problem can be modeled by a (directed) graph. The nodes are labeled 1, \dots, n. For each meetup and every i = 1, \dots, n, we add an edge from the node p_i to node i. Notice that the movement of a toy during a sequence of meetups is actually a path in this graph, and that every path also corresponds to a sequence of meetups. Also, in this graph it is true that if there is a path from node x to node y, then there is a path from y to x. Thus, the answer to the question is affirmative if and only if the nodes a and b are in the same connected component of the graph. The connected components can be found using BFS or DFS.


Comments

There are no comments at the moment.