Copies Without Originals#544

Solution

Track which initial card supplies the current contents of each card.

Let p_i be the index of the initial card whose contents are currently on card . Initially, p_i=i. For an operation , assign p_y=p_x. The initial numbers themselves are not needed for this simulation.

After all operations, the number a_i must have been written initially on card p_i. Therefore, if p_i=p_j but a_i\ne a_j, the given final contents are impossible and the answer is .

To check this, create an array of zeros. The value b_j=0 means that no requirement has yet been imposed on the initial contents of card . Zero can be used because all given numbers are positive.

Process cards from to . If b_{p_i}=0, set b_{p_i}=a_i and increase the answer by one. Otherwise, check that b_{p_i}=a_i. If this equality fails, print .

If there are no conflicts, the answer is the number of distinct values among p_1, p_2, \ldots, p_n.

Correctness proof

Initially, p_i=i correctly identifies the source of the contents of card . Copying from to changes the source of card to the source of card . Thus, the assignment p_y=p_x preserves the correctness of all values p_i after each operation.

Two final cards that come from the same initial card must have equal contents. Therefore, every conflict found by the algorithm means that the given final contents are indeed impossible.

If there are no conflicts, every initial card whose index appears among the values p_i must be non-empty: at least one non-empty final card comes from it. Hence, the answer cannot be smaller than the number of these initial cards.

Write the required number b_j on each of these initial cards and leave all other initial cards empty. After all operations, card will contain b_{p_i}=a_i. This produces the required contents with the minimum possible number of initially non-empty cards.

Complexity

Each operation and each card is processed in constant time. The time complexity is O(n+m) and the extra space is . Operations can be processed as they are read.