Official

A - Swap Digit Editorial by evima


For convenience, we assume that for \(0 \le i \le N-1\), the \(i\)-th (\(0\)-indexed) lowest digits of \(A\) and \(B\) are different.

Let \(a_i\) and \(b_i\) be the \(i\)-th lowest digits of \(A\) and \(B\), respectively. Then, we have:

\(\begin{aligned} A \times B &= \sum_{i=0}^{N-1} \sum_{j=0}^{N-1} a_ib_j10^{i+j} \\ &= \sum_{i=0}^{N-1} a_ib_i10^{2i} + \sum_{i=0}^{N-1} \sum_{j=i+1}^{N-1} (a_ib_j+a_jb_i) 10^{i+j}. \end{aligned}\)

The value \(\sum_{i=0}^{N-1} a_ib_i10^{2i}\) does not change no matter what we do. Our objective is to minimize \(\sum_{i=0}^{N-1} \sum_{j=i+1}^{N-1} (a_ib_j+a_jb_i) 10^{i+j}\).

Here, which of \(a_ib_j+a_jb_i\) and \(a_ib_i + a_jb_j\) is the smaller? If \(a_i-a_j\) and \(b_i-b_j\) have the same sign, the former; otherwise, the letter.

Proof $\begin{aligned} (a_ib_j+a_jb_i) - (a_ib_i + a_jb_j) &= a_i(b_j-b_i)+a_j(b_i-b_j) \\ &= (a_j-a_i)(b_i-b_j) \end{aligned}$

Thus, if $a_i-a_j$ and $b_i-b_j$ have the same sign, we have $a_ib_j + a_jb_i < a_ib_i + a_jb_j$; otherwise, we have $a_ib_j + a_jb_i > a_ib_i + a_jb_j$.

Therefore, we can minimize \(A \times B\) by specifying the smaller of \(a_i\) and \(b_i\) as \(a_i\) and the larger as \(b_i\).

Now, we can find \(\sum_{i=0}^{N-1} a_i10^i\) and \(\sum_{i=0}^{N-1} b_i10^i\) modulo \(998244353\) and compute their product to solve the problem in \(\mathrm{O}(N)\) time.

posted:
last update: