Solarium for mushrooms (Hard)#4361

Solarium for mushrooms (Hard) (Editorial)

Let us divide the set of points with integer coordinates into five parts, as shown in the figure: one point lies at the center, and the remaining four parts are symmetric and cover the four quadrants of the circle. If the number of points lying in one quadrant is , then the total number of points inside the circle will be 4 \cdot res + 1.

Let's compute the value of . Let the radius of the circle be . We iterate over the values of from to . Then, on the line y = k~(0 \le k \le r), there will be \left\lfloor {\sqrt{r^2 - k^2}}\right\rfloor points with integer coordinates lying inside the circle. The total number of such points across all y levels gives us the value of :

\sum_{k=0}^r \left\lfloor {\sqrt{r^2 - k^2}}\right\rfloor

Let denote the total number of integer-coordinate points inside a circle of radius . Then:

f(r) = 4 \cdot \sum_{k=0}^r \left\lfloor {\sqrt{r^2 - k^2}} \right\rfloor + 1

The function f is monotonically increasing. The task is to find the smallest value of such that the equation f(r) = n holds. We'll use binary search to find the required radius of the lamp.

Algorithm implementation

The function count returns the number of points with integer coordinates that lie inside a circle of radius .

long long count(long long r)
{
  long long res = 0;
  double r2 = r * r;
  for (long long y = 0; y <= r; y++)
    res += (long long)sqrt(r2 - y*y);
  return 4 * res + 1;
}

The main part of the program. Read the input value .

scanf("%lld",&n);

Search for the radius of the circle that covers at least n points using binary search. Initially, we assume that the desired radius lies within the range [l; r] = [0; 1000000].

l = 0; r = 1000000;
while (l < r)
{
   m = (l + r ) / 2;

If the number of points inside a circle of radius is less than , increase the left boundary of the interval to m + 1, the radius is not sufficient to cover points. Otherwise, decrease the right boundary.

   if (count (m) < n) l = m + 1; else r = m;
}

Print the answer.

printf("%d\n",l);