E - K-colinear Line Editorial by spheniscine


The constraints and time limit admit an \(O(N^3)\) solution, but with some thought this can be improved to \(O(N^2 \log)\). I challenge you to find it for yourself before reading on.

For each pair of points , you can find the equation of the line connecting them, in the form of \(Ax + By = C\), by the following assignments:

\(A = y_2 - y_1\)

\(B = x_1 - x_2\)

\(C = Ax_1 + By_1\)

The equation should then be normalized by dividing the coefficients by their common GCD, and by ensuring that the first non-zero coefficient is positive.

Put the normalized equations into a hashmap, counting the number of pairs that produced that line. Note that if there are \(K\) points on a line, then there are \(\frac {K(K-1)}2\) pairs that could have produced that line. So you just have to count the entries in the hashmap that have at least that number of pairs.

posted:
last update: