Back To School 2 (ANWCC05) - Unofficial Editorial

Problem (Contest): https://www.codechef.com/COCS2019/problems/ANWCC05

Problem Statement in brief:
Given points P,S and R, determine whether it is possible to draw a circle passing through S and R such that PS is a tangent. If possible then determine the length QR where Q intersection of line PR with the circle (other than R). If QR is zero, print -1.

Pre-requisites:
High school geometry lemmas.

Solution:
Such a circle is possible only when P,R,S are not collinear. So check for slopes of the lines PR and PS, i.e., \frac{y_p-y_r}{x_p-x_r}==\frac{y_p-y_s}{x_p-x_s}. Make separate checks to deal with cases when lines are parallel to y-axis (division by zero!).

Now we use the formula for Power of a point.
If such a circle exists, then pow(P)=PS^2=PQ\cdot PR.
Let QR=x. If R is closer to P than Q, then PQ=PR+x. If Q is closer, then PQ=PR-x.
So, PS^2=PR\cdot(PR\pm x)\Rightarrow \pm x=\frac{PS^2-PR^2}{PR}\Rightarrow x=\left|\frac{PS^2-PR^2}{PR}\right|.
Now just check if PS^2==PR^2, then print -1, otherwise compute the value of x and print it.
Required distance formula: PR^2=(x_p-x_r)^2+(y_p-y_r)^2.

Here is my solution.

//