Official

A - Hamming-Distant Arrays Editorial by evima


We assume that there exists a sequence \(y\) such that \(d(x_i,y)\leq N^2-N-1\) for all \(i\), and consider the necessary conditions that \(x_i\) must satisfy.

For each \(1 \leq j \leq N^2\), let \(c_j\) denote the number of \(i\) such that \(x_{i,j}=y_j\). Here, clearly \(\sum_{1 \leq j \leq N^2} c_j \geq N^2+N\).

Therefore, we obtain the following condition that \(x_i\) must satisfy:

  • For each \(1 \leq j \leq N^2\), let \(d_j\) be the number of occurrences of the mode (most frequent value) among \(x_{1,j},\cdots,x_{N,j}\). Then, \(\sum_{1 \leq j \leq N^2} d_j \geq N^2+N\).

Conversely, when \(x_i\) satisfies this condition, there exists a sequence \(y\) such that \(d(x_i,y)\leq N^2-N-1\) for all \(i\).

Specifically, \(y\) can be constructed as follows:

  • Let \(j_1,\cdots,j_k\) be the indices \(j\) where \(d_j \geq 2\). If \(k > N\), set \(k:=N\) and take only the first \(N\) indices.
  • For each \(1 \leq p \leq k\), set the value of \(y_{j_p}\) to the mode of \(x_{i,j_p}\).
  • When deciding the remaining elements \(y_j\), perform the following operation:
    • If there exists \(i\) such that the number of positions where \(x_i\) and \(y\) have matching values is at most \(N\), choose one such \(i\) and set \(y_j :=x_{i,j}\).

By focusing on the number of positions where \(x_i\) and \(y\) have matching values, we can prove the correctness of the above construction.

Once we understand this condition, the counting becomes a simple DP. Since \(N\) is small, any polynomial-time DP will work.

Sample solution (C++)

posted:
last update: