Log

What I read, built and learned, as it happens. Newest first.

allreadingprojectlearningproblemwriting

2026-10-14
problemCodeforces 1857F Sum and Product

Count pairs i<j with a_i+a_j=x and a_i*a_j=y for many queries. A scan per query is n*q, too slow. Let a,b = a[i],a[j], so b = x-a and y = a*(x-a), which gives a^2 - x*a + y = 0. The roots are (x +- sqrt(x^2-4y))/2, so each query has at most one value pair. Count with a frequency map: k*(k-1)/2 if the roots are equal, c_u*c_v if not. Accepted.

  • Sum and product together fix the pair of values, so the query reduces to a quadratic instead of a scan.
  • The discriminant x^2-4y must be a perfect square. x^2-4y fits in 64-bit, so no overflow.
problemLeetCode POTD: Maximize Sum of Squares of Digits