Editorial for DMOPC '23 Contest 1 P3 - Colour Scheme


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.

Author: dxke02

The intended solution is to build the array from left to right.

The problem is now, given a known prefix of the array, can you determine the next element?

We will represent a query on the interval [L,R] as Q(L,R).

Lets assume the first X elements of the array have already been determined, i.e B1,B2,...BX have been determined. To determine BX+1 we can first do a query on the interval [1,X+1]. There are now two cases.

Case 1: Q(1,X+1)=Q(1,X)+1

If Q(1,X+1)=Q(1,X)+1, it's clear that BX+1 will not have appeared yet, thus we know it is a new distinct element.

Case 2: Q(1,X+1)=Q(1,X)

This implies that BX+1 has already appeared among the first X elements, we just have to determine which one it is.

The key observation is that 1=Q(X+1,X+1)Q(X,X+1)Q(X1,X+1)Q(X2,X+1) ...Q(1,X+1), i.e Q(i,X+1) is monotonically increasing as i decreases. Clearly this is true since the number of distinct elements can only increase as the left end decreases. This motivates a binary search solution. Let C be a sorted array consisting of the indices of the last occurence of every distinct element in B1,B2,...BX. Observe that if BX+1=BC[i] then Q(C[i],X)=Q(C[i],X+1). In fact for all j<i we will have Q(C[j],X)=Q(C[j],X+1) (why?). With this in mind we can simply determine the last index of C where the equality holds with binary search, this index will be equal to BX+1. After determining BX+1, update the array C so that it considers BX+1 as a last occurence of some element.

The query complexity of this algorithm is (NK)logK, where K is the number of distinct elements in the array. With proper implementation, this should fit within the 50000 query limit. Partial points are meant for sub-optimal implementations of the full solution.

Time Complexity: O(N2)


Comments

There are no comments at the moment.