Editorial for COCI '07 Contest 2 #5 Kemija


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 smaller inputs (all numbers up to 100) we can try all possible pairs of values for the first two numbers in the ring (which uniquely determines all remaining numbers), calculate all remaining numbers and check if the ring generated by adding neighbours to a number is equal to the input ring.

For larger rings, the solution is much more complex. Label the numbers in the first ring A_1 to A_N, and the second ring B_1 to B_N. We need to find a ring A such that it generates ring B, and that all numbers in it are positive.

First, notice that the sum of ring A must be exactly one third of the sum of ring B.

Also, from the input ring we can determine for each position k the difference A_{k+3}-A_k = B_{k+2}-B_{k+1}. This, with the sum of ring B, suffices to solve the task.

When the length of ring N is not divisible by 3, the solution is unique. Suppose the first element of the ring (A_1) equals 1. From the calculated differences we determine A_4, A_7, \dots, A_{N-2}. Because N is relatively prime to 3, we will have determined all numbers A_2 to A_N before returning to A_1. We just need to ensure that the sum of ring A is appropriate (one third of the sum of ring B). For this it suffices to add to each element of A the value of the expression [sum(B)/3 - currentsum(A)] / N.

When N is divisible by 3, the solution is not unique and it is less obvious how to ensure that the numbers are positive. This time the differences generate three separate "chains":

  • A_1, A_4, \dots, A_{N-2};
  • A_2, A_5, \dots, A_{N-1};
  • A_3, A_6, \dots, A_N.

We need to determine the numbers A_1, A_2 and A_3 (and increase the numbers in their respective chains so that the differences are right) so that all numbers are positive and that the sum of ring A is correct. It is not hard to show that a ring which satisfies this generates the input ring B.

For each of the chains, it is possible to determine the smallest possible value of the first number so that all numbers in the chain are positive. For example, if the differences generate the chain 1, -4, 5, then we need to add at least 5 to all numbers so that all numbers are positive.

We can set A_1 to the smallest value so that the first chain is positive (in the previous example A_1 would be 6) and similarly for A_2 and the second chain. A_3 is uniquely determined by the expression B_2-A_1-A_2.


Comments

There are no comments at the moment.