Official

I - K-th Largest Triplet Editorial by en_translator


Sort each of \(A\), \(B\), and \(C\) in descending order. Also, let \(f(i,j,k)=A_iB_j+B_jC_k+C_kA_i\). Since

\[f(i,j,k)\geq f(i+1,j,k),f(i,j,k)\geq f(i,j+1,k),f(i,j,k)\geq f(i,j,k+1),\]

the number of possible tuples \((i,j,k)\) satisfies \(ijk\leq K\). Thus, one can evaluate \(f(i,j,k)\) for each such \((i,j,k)\), and find the \(K\)-th largest among them.

There are \(O(K\log^2K)\) tuples with \(ijk\leq K\). (For \(K=5\times 10^5\), the count is \(48094156\approx 4.8\times 10^7\).) While sorting a sequence of length \(O(K\log^2 K)\) will not finish within the time limit, one can use nth_element in C++ for example to find the \(K\)-th largest element within the time limit as long as the language is fast.

Notes: there are \(O(K\log^2K)\) tuples with \(ijk\leq K\) because \(\displaystyle\int_1^K\left(\int_1^{K/x}\left(\int_{1}^{K/(xy)}1dz\right)dy\right)dx=O(K\log^2K)\).

posted:
last update: