Editorial for COCI '22 Contest 5 #2 Diskurs


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.

Let's look at the numbers as bitstrings of length m. For a number x, let xc be a number that has flipped binary representation.

For example, for m=5 and x=13 it follows xc=18 because x=011012 and xc=100102. Exactly xc would be the ideal candidate for the biggest Hamming distance with x, but xc is not necessarily a part of a.

Let us describe two possible solutions:

Solution 1

First solution is based on the fact that

maxyahamming(x,y)=mminyahamming(xc,y)

Intuitively, we want a number as similar to xc as possible.

Let us try to calculate the minimal Hamming distance for every number in [0,2m1]. For every number that appears in a it is 0. It leads us to a BFS solution, where each number in [0,2m1] is a node in our graph and the edges represent changing exactly one bit. In a graph constructed in such a fashion Hamming distance between two numbers is exactly the length of shortest path between corresponding nodes. So we start BFS algorithm with every number from a in our queue and we will get the desired minimal distances.

Solution 2

Second solution is based on dynamic programming. Let popcount(x) be the number of ones in the binary representation of x. The solution will be based on the following identity:

hamming(x,y)=popcount(x)+popcount(y)2popcount(x&y)

Intuitively, each one in the binary representation of each number contributes 1 to Hamming distance, but then each common one decreases it by 2.

We want to calculate dp(mask) - maximum number of ones for some number in a but each one that is not in mask we penalize by 2. Formally,

dp(mask)=maxxa(popcount(x)2popcount(x&maskc))

Then, the solution for some x will be given as popcount(x)+dp(xc). The above dp can be calculated with standard dp with bitmasks methods.

Complexity of both solutions is O(2mm).


Comments

There are no comments at the moment.