Editorial for LCC '21 Contest 1 S4 - Perfect Squares
Submitting an official solution before solving the problem yourself is a bannable offence.
Author:
Subtask 1
When coding a naive solution for the problem, we simply multiply all of the numbers from a given range to , before checking if it is a perfect square. However, the product of these numbers will quickly overflow the integer data type so it is not enough to pass the first subtask. To solve the first subtask, the storage of numbers must be condensed.
Let be the product of the numbers in a query which has the prime factors, .
We observe that if all the prime factors of are raised to an even power then it is a perfect square. This is because can be represented as a square of where is the exponent to which that prime factor is raised. Following this idea, we convert the numbers on each card into their prime factorizations. One possible algorithm for prime factorization is the Sieve of Eratosthenes.
To complete a query, we add up the powers for a given prime factor and check that it is even. If every prime factor passes this check, then we can output yes
Subtask 2
For the second subtask, we notice that only the parity of is relevant. Thus each prime factor can be represented by two states, for an even exponent and for an odd exponent. Every number can then be represented as a collection of s and s, a bitset. For example, can be represented as or . In order to combine the parity of two sets of prime factors, we must perform the XOR operation on their bitsets.
Now that we have the prime factors represented as bits, we can combine the parity of two sets of prime factors in , however, each query still takes time.
Our next observation is that XOR is a commutative operation and as such we can create a Prefix XOR Array (PXA). Similar to the Prefix Sum Array (PSA) which stores the sum of all numbers up the current index, the PXA will store the XORs of all numbers up to the current index.
Recall that the sum of numbers between and in a PSA is
Similarly, to find the XORs of numbers between and we write
Using this optimization, queries can be answered in time.
Comments