Editorial for COCI '21 Contest 5 #4 Radio


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 each broadcasting radio frequency x, we can keep track of two other radio frequencies Lx and Rx, the next smallest and the next largest broadcasting frequency which makes noise with x (if Lx doesn't exist, we take it to be 1, and if Rx doesn't exist, we take it to be 109). The interval [l,r] creates noise if maxx[l,r]Lxl or minx[l,r]Rxr. The minimum and maximum in the interval can be determined in O(logn) using a segment tree. What remains is to figure out a way to keep track of Lx and Rx.

Notice that two frequencies create noise if and only if they are both divisible by some prime number. If in the sieve of Eratosthenes, we store for each number one of its prime factors, then we can factor a number in O(logn) by going over each of its prime factors. For each prime, we can maintain a set of broadcasting frequencies divisible by this prime. Then for each frequency, there are at most O(logn) candidates for Lx and Rx.

These observations are sufficient to obtain a solution. When a frequency x becomes active, for each prime factor of x, we look at the set of broadcasting frequencies for that prime and we find the next smallest and next largest frequency in this set. The minimum of the larger frequencies will be Rx, and the maximum of the smaller frequencies will be Lx. Additionally, for each of the Lx and Rx candidates, their L and R values might change, so we must update them. The number of candidates is O(logn), and updating Lx or Rx takes O(logn). Therefore, we can keep track of the updates in O(log2n). When deactivating a frequency, we do the opposite. We erase the number x from all the sets it is in, and adjust Lx and Rx of its neighbours. Again, the number of neighbours is O(logn).

It should be noted that the time complexity is in practice even better because numbers less than 106 can have at most 7 distinct prime factors since 235711131719>106.


Comments

There are no comments at the moment.