Editorial for Google Code Jam '22 Round 1C Problem B - Squary


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.

The multinomial expansion for the power of 2 is the key to solving this problem. The expansion of the square of the sum of elements X1,X2,,Xn in the list X looks like:

square of sum=(X1+X2+X3++XN)2=X12+X22+X32++XN2+2X1X2+2X2X3+2X1X3++2XN1XN=sum of squares+2sum of pairwise products

Let S(X) be the sum of elements, SQ(X) be the sum of squares of elements, and SP(X) be the sum of all pairwise products of elements of the list X. We can now rewrite the above equation as:

S(X)2=SQ(X)+2SP(X)

We can also observe the following about how the above values change when an additional element n is added to the list X:

S(X+[n])=S(X)+nSQ(X+[n])=SQ(X)+n2SP(X+[n])=SP(X)+nS(X)

Our task is to achieve S(E)2=SQ(E), where E is the extended list that we get by adding extra elements to E. In other words, we want to make SP(E)=0.

Test Set 1: K=1

If we are allowed only a single addition, we must choose an element n such that SP(E+[n])=0.

SP(E+[n])=0SP(E)+nS(E)=0nS(E)=SP(E)

If S(E)0, we can get a squary list whenever SP(E)/S(E) is an integer, which happens if and only if S(E) divides SP(E). In that case, SP(E)/S(E) is our answer.

If S(E)=0, then S(E+[n])=n. Since we want S(E+[n])2=SQ(E+[n]), we need SQ(E+[n])=n2. This is possible only if SQ(E)=0, that is, if all elements in E are zeros. In this case, we can choose any value as our answer. But if any element in E is not zero, it is impossible to get a squary list with only one addition.

Test Set 2: K>1

At first, the search space might seem hopelessly broad here. But we can observe (or surmise and then confirm) that it is always possible to get a squary list by adding only two elements:

  • n1=1S(E)
  • n2=SP(E+[n1])

After adding n1, we have

S(E+[n1])=1

After adding n2, we have

SP(E+[n1,n2])=SP(E+[n1])+n2S(E+[n1])=SP(E+[n1])+(SP(E+[n1]))1=0

Thus, the two numbers satisfy the condition SP(E)=0. We can also see that since the numbers in the original list are each of magnitude no greater than 103, |n1|106+1, and |n2|21012, both well within the limits.


Comments

There are no comments at the moment.