Problem:
MathJax.Hub.Config({ tex2jax: { inlineMath: [["$","$"], ["\\(","\\)"]], processEscapes: true }});

Intersection of a Circle and a Polygon

Find the area of intersection between a circle $c$ and a polygon $g$. The center coordinate of the circle is ($0, 0$).

The polygon $g$ is represented by a sequence of points $p_1$, $p_2$,..., $p_n$ where line segments connecting $p_i$ and $p_{i+1}$ ($1 \leq i \leq n−1$) are sides of the polygon. The line segment connecting $p_n$ and $p_1$ is also a side of the polygon.

Note that the polygon is not necessarily convex.

Input

The input is given in the following format.

$n$ $r$

$x_1$ $y_1$

$x_2$ $y_2$

:

$x_n$ $y_n$

In the first line, an integer n representing the number of points in the polygon is given. The coordinate of a point $p_i$ is given by two integers $x_i$ and $y_i$. The coordinates of the points are given in the order of counter-clockwise visit of them. All input values are given in integers.

Constraints

$3 \leq n \leq 100$

$1 \leq r \leq 100$

$-100 \leq x_i, y_i \leq 100$

Output

Print the area of intersection in a line.
The output values should be in a decimal fraction with an error less than 0.00001.

Sample Input 1

3 5
1 1
4 1
5 5

Sample Output 1

4.639858417607

Sample Input 2

4 5
0 0
-3 -6
1 -3
5 -4

Sample Output 2

11.787686807576

Solution in Python (judge verdict: Accepted)

n, r = map(int, raw_input().split())
P = [map(int, raw_input().split()) for i in xrange(n)]

from math import sqrt, atan2

def intersection01(cx, cy, r, x1, y1, x2, y2):
    xd = x2 - x1; yd = y2 - y1
    X = x1 - cx; Y = y1 - cy
    a = xd**2 + yd**2
    b = xd * X + yd * Y
    c = X**2 + Y**2 - r**2
    D = b**2 - a*c
    result = []
    if D > 0:
        d = sqrt(D)
        if 0 < -b - d < a:
            s = (-b - d) / a
            result.append((x1 + xd*s, y1 + yd*s))
        if 0 < -b + d < a:
            s = (-b + d) / a
            result.append((x1 + xd*s, y1 + yd*s))
    elif D == 0:
        if 0 < -b < a:
            s = -b / float(a)
            result.append((x1 + xd*s, y1 + yd*s))
    return result

def calc(x0, y0, x1, y1, rr):
    if x0**2 + y0**2 - rr <= 1e-8 and x1**2 + y1**2 - rr <= 1e-8:
        return (x0 * y1 - x1 * y0) / 2.
    theta = atan2(x0*y1 - x1*y0, x0*x1 + y0*y1)
    return theta*rr/2.

rr = r**2
ans = 0
for i in xrange(n):
    (x0, y0) = P[i-1]; (x1, y1) = P[i]

    result = intersection01(0, 0, r, x0, y0, x1, y1)
    px = x0; py = y0
    for x, y in result:
        ans += calc(px, py, x, y, rr)
        px = x; py = y
    ans += calc(px, py, x1, y1, rr)
print "%.08f" % ans