<|instruction|>
Solve the below problem. The solution should start with an abridged problem statement. Then key observations. Then full solution based on the observations. Then C++ and Python implementations with comments.

412. Expedition
Time limit per test: 0.75 second(s)
Memory limit: 65536 kilobytes
input: standard
output: standard

Summer comes! Peter waited for it a lot. This is not surprising — Peter goes to his first geological expedition. And do you know what is the main item at the expedition? Certainly, large tent. Peter noticed that when tent is put up, it has the shape of convex polygon with N vertices while observing from above. But it is not enough to take only a tent. Peter will need other equipment. It was decided to place all the equipment at M shelves inside the tent. Each shelf is infinitely narrow, so it can be represented as a segment at the scheme of the tent. Shelves are made differently, so corresponding segments can touch or intersect each other. Also Peter puts a lamp to the center of the tent. At the scheme the lamp has (0,0) coordinates. Peter noticed, that shelves block the light, so part of tent's walls becomes shaded. Peter has remembered, that he'd left his boots near some wall. To decide, how difficult it would be to find them, Peter needs to know, what is the total length of walls' shaded parts? Could you help him to find the answer for this question?
Input
There are two integers at the first line of input — N and M (3 ≤ N ≤ 100000, 0 ≤ M ≤ 100000) — number of vertices in polygon, which tent is represented by, and the number of shelves. Following N lines contain 2 integers each (xi, yi) — coordinates of i-th vertex of polygon. Vertices are given in counter-clockwise order. Following M lines contain 4 integers  —coordinates of the segment, which represents j-th shelf. All coordinates in the input do not exceed 106 by absolute value. It is guaranteed, that the point (0,0) and each segment lie strictly inside the polygon. None of segments contains the point (0, 0).
Output
Output answer for the problem with at least 6 digits after decimal point.
Example(s)
sample input
sample output
3 1
0 2
-2 -1
3 -3
-1 -1 1 -1
4.615855548972
Explanatory picture:


sample input
sample output
4 3
-2 -2
2 -2
2 2
-2 2
-1 0 0 -1
1 -1 1 1
-1 1 1 1
12.000000
Explanatory picture:

<|response|>
## 1. Abridged problem statement

A convex polygon with `N` vertices represents the tent boundary. The lamp is at the origin `(0, 0)`, strictly inside the polygon.

There are `M` shelves, each represented by a segment strictly inside the polygon. A shelf blocks light along every ray from the origin that intersects the shelf. The blocked rays shade corresponding parts of the polygon boundary.

Compute the total length of shaded parts of the polygon boundary.

Constraints:

```text
3 ≤ N ≤ 100000
0 ≤ M ≤ 100000
```

The polygon is convex, vertices are given counter-clockwise, all shelves are inside the polygon, and no shelf contains the origin.

---

## 2. Key observations needed to solve the problem

### Observation 1: Boundary points correspond to directions

Because the polygon is convex and the origin is strictly inside it, every ray starting from the origin intersects the polygon boundary in exactly one point.

So there is a one-to-one correspondence:

```text
angle θ  <->  point on polygon boundary hit by ray θ
```

Thus, instead of directly working with boundary segments, we can work with angular intervals.

---

### Observation 2: Each shelf blocks one angular interval

A shelf is a segment `AB`.

From the origin, this segment subtends an angular interval between the directions of points `A` and `B`.

Let:

```cpp
angle(A) = atan2(A.y, A.x)
angle(B) = atan2(B.y, B.x)
```

The segment does not contain the origin, so the blocked angular interval is always the smaller arc between the two endpoint directions.

The cross product determines its direction:

```cpp
cross(A, B) = A.x * B.y - A.y * B.x
```

- If `cross(A, B) > 0`, the blocked interval is from `angle(A)` to `angle(B)` counter-clockwise.
- If `cross(A, B) < 0`, the blocked interval is from `angle(B)` to `angle(A)` counter-clockwise.
- If `cross(A, B) == 0`, the segment has zero angular width and contributes nothing.

Intervals crossing angle `0` are split into two intervals.

---

### Observation 3: Merge all blocked angular intervals

After converting all shelves into angular intervals, the shaded directions are simply the union of those intervals.

Sort the intervals and merge overlapping ones.

---

### Observation 4: Convert an angular interval to polygon boundary length

For a blocked angular interval `[l, r]`, we need the length of the polygon boundary swept by rays with angles from `l` to `r`.

Because the polygon is convex and contains the origin, sorting polygon vertices by polar angle gives the same cyclic order as walking along the boundary.

We can precompute:

```text
bound[i] = polar angle of vertex i
pref[i]  = boundary length from vertex 0 to vertex i
```

For any angle `θ`, binary search which polygon edge is hit by the ray. Then intersect the ray with that edge and compute the distance along the boundary from the starting vertex.

Define:

```text
S(θ) = boundary distance from chosen starting vertex to boundary point hit by ray θ
```

Then:

```text
length of boundary for interval [l, r] = S(r) - S(l)
```

with special handling for cyclic wraparound.

---

## 3. Full solution approach

### Step 1: Read input

Read the convex polygon and shelf segments.

---

### Step 2: Sort polygon vertices by angle

For every polygon vertex `P`, compute:

```cpp
atan2(P.y, P.x)
```

Normalize the angle to `[0, 2π)`.

Sort vertices by angle.

Since the polygon is convex and the origin is inside it, this sorted order is exactly a cyclic boundary order.

---

### Step 3: Precompute prefix boundary lengths

For sorted polygon vertices `poly[0], poly[1], ..., poly[n - 1]`, compute:

```cpp
pref[0] = 0
pref[i] = pref[i - 1] + distance(poly[i - 1], poly[i])
```

Also compute the full perimeter:

```cpp
perimeter = pref[n - 1] + distance(poly[n - 1], poly[0])
```

---

### Step 4: Define a function `arcLength(theta)`

This function returns the boundary distance from `poly[0]` to the point where the ray with direction `theta` hits the polygon.

To compute it:

1. Binary search the polygon edge whose angular range contains `theta`.
2. Intersect the ray from the origin with that edge.
3. Return prefix distance to the edge start plus distance along the edge to the intersection point.

---

### Step 5: Convert shelves to angular intervals

For each shelf segment `AB`:

1. Compute endpoint angles.
2. Use cross product to determine the correct counter-clockwise interval.
3. If the interval crosses `0`, split it.

Collect all intervals.

---

### Step 6: Merge intervals

Sort all angular intervals by start angle.

Then merge overlapping or touching intervals.

---

### Step 7: Convert merged intervals to boundary length

For each merged interval `[l, r]`, compute its shaded boundary length using `arcLength`.

Because `arcLength` is parameterized starting from the smallest polygon vertex angle `g0`, there are three cases:

1. Entire interval is before `g0`: shift by `2π`.
2. Entire interval is after `g0`: use directly.
3. Interval contains `g0`: split around the cyclic boundary start.

Accumulate all contributions.

---

### Complexity

Sorting polygon vertices:

```text
O(N log N)
```

Sorting shelf intervals:

```text
O(M log M)
```

Each merged interval uses binary search:

```text
O(log N)
```

Overall complexity:

```text
O((N + M) log(N + M))
```

Memory usage:

```text
O(N + M)
```

---

## 4. C++ Solution

```cpp
#include <bits/stdc++.h>
// #include <coding_library/geometry/point.hpp>

using namespace std;

template<typename T1, typename T2>
ostream& operator<<(ostream& out, const pair<T1, T2>& x) {
    return out << x.first << ' ' << x.second;
}

template<typename T1, typename T2>
istream& operator>>(istream& in, pair<T1, T2>& x) {
    return in >> x.first >> x.second;
}

template<typename T>
istream& operator>>(istream& in, vector<T>& a) {
    for(auto& x: a) {
        in >> x;
    }
    return in;
};

template<typename T>
ostream& operator<<(ostream& out, const vector<T>& a) {
    for(auto x: a) {
        out << x << ' ';
    }
    return out;
};

using coord_t = double;

struct Point {
    static constexpr coord_t eps = 1e-9;
    static inline const coord_t PI = acos((coord_t)-1.0);

    coord_t x, y;
    Point(coord_t x = 0, coord_t y = 0) : x(x), y(y) {}

    Point operator+(const Point& p) const { return Point(x + p.x, y + p.y); }
    Point operator-(const Point& p) const { return Point(x - p.x, y - p.y); }
    Point operator*(coord_t c) const { return Point(x * c, y * c); }
    Point operator/(coord_t c) const { return Point(x / c, y / c); }

    coord_t operator*(const Point& p) const { return x * p.x + y * p.y; }
    coord_t operator^(const Point& p) const { return x * p.y - y * p.x; }

    bool operator==(const Point& p) const { return x == p.x && y == p.y; }
    bool operator!=(const Point& p) const { return x != p.x || y != p.y; }
    bool operator<(const Point& p) const {
        return x != p.x ? x < p.x : y < p.y;
    }
    bool operator>(const Point& p) const {
        return x != p.x ? x > p.x : y > p.y;
    }
    bool operator<=(const Point& p) const {
        return x != p.x ? x < p.x : y <= p.y;
    }
    bool operator>=(const Point& p) const {
        return x != p.x ? x > p.x : y >= p.y;
    }

    coord_t norm2() const { return x * x + y * y; }
    coord_t norm() const { return sqrt(norm2()); }
    coord_t angle() const { return atan2(y, x); }

    Point rotate(coord_t a) const {
        return Point(x * cos(a) - y * sin(a), x * sin(a) + y * cos(a));
    }

    Point perp() const { return Point(-y, x); }
    Point unit() const { return *this / norm(); }
    Point normal() const { return perp().unit(); }
    Point project(const Point& p) const {
        return *this * (*this * p) / norm2();
    }
    Point reflect(const Point& p) const {
        return *this * 2 * (*this * p) / norm2() - p;
    }

    friend ostream& operator<<(ostream& os, const Point& p) {
        return os << p.x << ' ' << p.y;
    }
    friend istream& operator>>(istream& is, Point& p) {
        return is >> p.x >> p.y;
    }

    friend int ccw(const Point& a, const Point& b, const Point& c) {
        coord_t v = (b - a) ^ (c - a);
        if(-eps <= v && v <= eps) {
            return 0;
        } else if(v > 0) {
            return 1;
        } else {
            return -1;
        }
    }

    friend bool point_on_segment(
        const Point& a, const Point& b, const Point& p
    ) {
        return ccw(a, b, p) == 0 && p.x >= min(a.x, b.x) - eps &&
               p.x <= max(a.x, b.x) + eps && p.y >= min(a.y, b.y) - eps &&
               p.y <= max(a.y, b.y) + eps;
    }

    friend bool point_in_triangle(
        const Point& a, const Point& b, const Point& c, const Point& p
    ) {
        int d1 = ccw(a, b, p);
        int d2 = ccw(b, c, p);
        int d3 = ccw(c, a, p);
        return (d1 >= 0 && d2 >= 0 && d3 >= 0) ||
               (d1 <= 0 && d2 <= 0 && d3 <= 0);
    }

    friend Point line_line_intersection(
        const Point& a1, const Point& b1, const Point& a2, const Point& b2
    ) {
        return a1 +
               (b1 - a1) * ((a2 - a1) ^ (b2 - a2)) / ((b1 - a1) ^ (b2 - a2));
    }

    friend bool collinear(const Point& a, const Point& b) {
        return abs(a ^ b) < eps;
    }

    friend Point circumcenter(const Point& a, const Point& b, const Point& c) {
        Point mid_ab = (a + b) / 2.0;
        Point mid_ac = (a + c) / 2.0;
        Point perp_ab = (b - a).perp();
        Point perp_ac = (c - a).perp();
        return line_line_intersection(
            mid_ab, mid_ab + perp_ab, mid_ac, mid_ac + perp_ac
        );
    }

    friend coord_t arc_area(
        const Point& center, coord_t r, const Point& p1, const Point& p2
    ) {
        coord_t theta1 = (p1 - center).angle();
        coord_t theta2 = (p2 - center).angle();
        if(theta2 < theta1 - eps) {
            theta2 += 2 * PI;
        }

        coord_t d_theta = theta2 - theta1;
        coord_t cx = center.x, cy = center.y;
        coord_t area = r * cx * (sin(theta2) - sin(theta1)) -
                       r * cy * (cos(theta2) - cos(theta1)) + r * r * d_theta;
        return area / 2.0;
    }

    friend vector<Point> intersect_circles(
        const Point& c1, coord_t r1, const Point& c2, coord_t r2
    ) {
        Point d = c2 - c1;
        coord_t dist = d.norm();

        if(dist > r1 + r2 + eps || dist < abs(r1 - r2) - eps || dist < eps) {
            return {};
        }

        coord_t a = (r1 * r1 - r2 * r2 + dist * dist) / (2 * dist);
        coord_t h_sq = r1 * r1 - a * a;
        if(h_sq < -eps) {
            return {};
        }
        if(h_sq < 0) {
            h_sq = 0;
        }
        coord_t h = sqrt(h_sq);

        Point mid = c1 + d.unit() * a;
        Point perp_dir = d.perp().unit();

        if(h < eps) {
            return {mid};
        }
        return {mid + perp_dir * h, mid - perp_dir * h};
    }

    friend optional<Point> intersect_ray_segment(
        const Point& ray_start, const Point& ray_through, const Point& seg_a,
        const Point& seg_b
    ) {
        Point ray_dir = ray_through - ray_start;
        if(ray_dir.norm2() < Point::eps) {
            return {};
        }
        Point seg_dir = seg_b - seg_a;
        coord_t denom = ray_dir ^ seg_dir;
        if(fabs(denom) < eps) {
            return {};
        }
        coord_t t = ((seg_a - ray_start) ^ seg_dir) / denom;
        if(t < eps) {
            return {};
        }
        coord_t s = ((seg_a - ray_start) ^ ray_dir) / denom;
        if(s < eps || s > 1 - eps) {
            return {};
        }
        return ray_start + ray_dir * t;
    }
};

namespace fastin {
const int BUF = 1 << 16;
char buf[BUF];
int pos = 0, len = 0;

char gc() {
    if(pos == len) {
        len = (int)fread(buf, 1, BUF, stdin);
        pos = 0;
        if(len == 0) {
            return -1;
        }
    }
    return buf[pos++];
}

int64_t read_int() {
    char c = gc();
    while(c != '-' && (c < '0' || c > '9')) {
        c = gc();
    }
    bool neg = c == '-';
    if(neg) {
        c = gc();
    }
    int64_t x = 0;
    while(c >= '0' && c <= '9') {
        x = x * 10 + (c - '0');
        c = gc();
    }
    return neg ? -x : x;
}
}  // namespace fastin

int n, m;
vector<Point> poly;
vector<pair<Point, Point>> shelves;

void read() {
    n = fastin::read_int();
    m = fastin::read_int();
    poly.resize(n);
    for(auto& p: poly) {
        p.x = fastin::read_int();
        p.y = fastin::read_int();
    }
    shelves.resize(m);
    for(auto& [a, b]: shelves) {
        a.x = fastin::read_int();
        a.y = fastin::read_int();
        b.x = fastin::read_int();
        b.y = fastin::read_int();
    }
}

void solve() {
    // The lamp at the origin lies strictly inside the convex polygon, so a
    // ray cast in direction theta hits the boundary in exactly one point,
    // giving a bijection between angles theta in [0, 2*pi) and wall points.
    // A wall point is shaded exactly when its ray is blocked by some shelf,
    // so the answer is the boundary length of the wall points whose angle
    // lies in the union of the angular intervals occupied by the shelves.
    //
    // Each shelf is a segment that does not pass through the origin, so as
    // seen from the origin it spans the minor arc (less than pi) between the
    // angles of its endpoints; the sign of the cross product of the two
    // endpoint vectors tells us which of the two is the counter-clockwise
    // start of that arc. We cut every arc at angle 0 so all blocked
    // intervals live in [0, 2*pi), then sort and merge them.
    //
    // To turn a blocked angular interval into a wall length we sort the
    // polygon vertices by angle. Because the polygon is convex and the
    // origin is inside, this is just a rotation of the input order, so
    // consecutive sorted vertices stay adjacent on the boundary. Walking
    // the boundary counter-clockwise from the first sorted vertex, the
    // travelled distance s(theta) to the point hit at angle theta is a
    // monotone function, precomputed via prefix sums of edge lengths plus
    // the offset of the ray-edge intersection inside the current edge. The
    // contribution of a blocked interval [a, b] is then s(b) - s(a), with
    // intervals that straddle the anchor angle split across the wrap.

    auto norm_angle = [](coord_t a) {
        if(a < 0) {
            a += 2 * Point::PI;
        }
        return a;
    };

    vector<pair<coord_t, Point>> by_angle(n);
    for(int i = 0; i < n; i++) {
        by_angle[i] = {norm_angle(poly[i].angle()), poly[i]};
    }
    sort(by_angle.begin(), by_angle.end(), [](const auto& p, const auto& q) {
        return p.first < q.first;
    });

    vector<coord_t> bound(n + 1), pref(n + 1, 0);
    for(int i = 0; i < n; i++) {
        poly[i] = by_angle[i].second;
        bound[i] = by_angle[i].first;
        if(i > 0) {
            pref[i] = pref[i - 1] + (poly[i] - poly[i - 1]).norm();
        }
    }
    bound[n] = bound[0] + 2 * Point::PI;
    coord_t perim = pref[n - 1] + (poly[0] - poly[n - 1]).norm();

    coord_t g0 = bound[0];
    auto arc_length = [&](coord_t theta) {
        int i =
            upper_bound(bound.begin(), bound.end(), theta) - bound.begin() - 1;
        i = min(i, n - 1);
        Point dir(cos(theta), sin(theta));
        Point hit = line_line_intersection(
            Point(0, 0), dir, poly[i], poly[(i + 1) % n]
        );
        return pref[i] + (hit - poly[i]).norm();
    };

    vector<pair<coord_t, coord_t>> arcs;
    auto add_arc = [&](coord_t s, coord_t e) {
        if(s <= e) {
            arcs.emplace_back(s, e);
        } else {
            arcs.emplace_back(s, 2 * Point::PI);
            arcs.emplace_back(0, e);
        }
    };

    for(auto& [a, b]: shelves) {
        coord_t cross = a ^ b;
        if(fabs(cross) < Point::eps) {
            continue;
        }
        coord_t sa = norm_angle(a.angle()), sb = norm_angle(b.angle());
        if(cross > 0) {
            add_arc(sa, sb);
        } else {
            add_arc(sb, sa);
        }
    }

    sort(arcs.begin(), arcs.end());

    coord_t ans = 0;
    coord_t cur_lo = 0, cur_hi = -1;
    auto flush = [&]() {
        if(cur_hi < cur_lo) {
            return;
        }
        if(cur_lo < g0 - Point::eps && cur_hi > g0 + Point::eps) {
            ans += (perim - arc_length(cur_lo + 2 * Point::PI)) +
                   arc_length(cur_hi);
        } else if(cur_hi <= g0 + Point::eps) {
            ans += arc_length(cur_hi + 2 * Point::PI) -
                   arc_length(cur_lo + 2 * Point::PI);
        } else {
            ans += arc_length(cur_hi) - arc_length(cur_lo);
        }
    };

    for(auto& [s, e]: arcs) {
        if(cur_hi < cur_lo) {
            cur_lo = s;
            cur_hi = e;
        } else if(s <= cur_hi + Point::eps) {
            cur_hi = max(cur_hi, e);
        } else {
            flush();
            cur_lo = s;
            cur_hi = e;
        }
    }
    flush();

    cout << fixed << setprecision(12) << ans << '\n';
}

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr);

    int T = 1;
    // cin >> T;
    for(int test = 1; test <= T; test++) {
        read();
        solve();
    }

    return 0;
}
```

---

## 5. Python implementation with detailed comments

```python
import sys
import math
import bisect


EPS = 1e-12
PI = math.pi
TWO_PI = 2.0 * math.pi


def norm_angle(a):
    """
    Normalize angle to [0, 2*pi).
    """
    if a < 0:
        a += TWO_PI
    return a


def cross(a, b):
    """
    Cross product of vectors a and b.
    Points are represented as tuples (x, y).
    """
    return a[0] * b[1] - a[1] * b[0]


def dist(a, b):
    """
    Euclidean distance between two points.
    """
    return math.hypot(a[0] - b[0], a[1] - b[1])


def line_ray_edge_intersection(theta, p, q):
    """
    Intersect the line from origin in direction theta
    with the line containing polygon edge p -> q.

    The chosen edge is correct, so the intersection lies on that edge.
    """
    dx = math.cos(theta)
    dy = math.sin(theta)

    ex = q[0] - p[0]
    ey = q[1] - p[1]

    # Solve:
    # t * direction = p + u * edge
    #
    # Taking cross product with edge:
    # t * cross(direction, edge) = cross(p, edge)
    denom = dx * ey - dy * ex
    numer = p[0] * ey - p[1] * ex

    t = numer / denom

    return (dx * t, dy * t)


def solve():
    data = list(map(int, sys.stdin.buffer.read().split()))

    idx = 0

    n = data[idx]
    m = data[idx + 1]
    idx += 2

    polygon = []

    for _ in range(n):
        x = data[idx]
        y = data[idx + 1]
        idx += 2
        polygon.append((float(x), float(y)))

    shelves = []

    for _ in range(m):
        x1 = data[idx]
        y1 = data[idx + 1]
        x2 = data[idx + 2]
        y2 = data[idx + 3]
        idx += 4

        shelves.append(((float(x1), float(y1)), (float(x2), float(y2))))

    """
    Sort polygon vertices by polar angle.

    For a convex polygon containing the origin, this order is the same as
    walking along the polygon boundary, up to cyclic shift.
    """
    by_angle = []

    for p in polygon:
        ang = norm_angle(math.atan2(p[1], p[0]))
        by_angle.append((ang, p))

    by_angle.sort()

    polygon = [p for _, p in by_angle]

    bound = [ang for ang, _ in by_angle]

    """
    Add artificial closing angle.
    """
    bound.append(bound[0] + TWO_PI)

    """
    Prefix boundary lengths from polygon[0].
    """
    pref = [0.0] * (n + 1)

    for i in range(1, n):
        pref[i] = pref[i - 1] + dist(polygon[i - 1], polygon[i])

    perimeter = pref[n - 1] + dist(polygon[n - 1], polygon[0])

    start_angle = bound[0]

    def boundary_distance(theta):
        """
        Return boundary distance from polygon[0] to the point where
        the ray with angle theta hits the polygon.

        theta must be in [start_angle, start_angle + 2*pi].
        """
        edge = bisect.bisect_right(bound, theta) - 1

        if edge >= n:
            edge = n - 1

        p = polygon[edge]
        q = polygon[(edge + 1) % n]

        hit = line_ray_edge_intersection(theta, p, q)

        return pref[edge] + dist(p, hit)

    """
    Convert each shelf into one angular interval.
    """
    intervals = []

    def add_interval(l, r):
        """
        Add counter-clockwise interval from l to r.
        If it crosses angle 0, split it.
        """
        if l <= r:
            intervals.append((l, r))
        else:
            intervals.append((l, TWO_PI))
            intervals.append((0.0, r))

    for a, b in shelves:
        c = cross(a, b)

        """
        If the cross product is zero, the shelf has zero angular width.
        """
        if abs(c) < EPS:
            continue

        angle_a = norm_angle(math.atan2(a[1], a[0]))
        angle_b = norm_angle(math.atan2(b[1], b[0]))

        """
        Choose the smaller counter-clockwise angular interval.
        """
        if c > 0:
            add_interval(angle_a, angle_b)
        else:
            add_interval(angle_b, angle_a)

    """
    Sort and merge angular intervals.
    """
    intervals.sort()

    def interval_boundary_length(l, r):
        """
        Convert angular interval [l, r] to boundary length.
        """
        if l < start_angle - EPS and r > start_angle + EPS:
            return (perimeter - boundary_distance(l + TWO_PI)) + \
                   boundary_distance(r)

        if r <= start_angle + EPS:
            return boundary_distance(r + TWO_PI) - \
                   boundary_distance(l + TWO_PI)

        return boundary_distance(r) - boundary_distance(l)

    answer = 0.0

    cur_l = 0.0
    cur_r = -1.0

    for l, r in intervals:
        if cur_r < cur_l:
            cur_l = l
            cur_r = r
        elif l <= cur_r + EPS:
            cur_r = max(cur_r, r)
        else:
            answer += interval_boundary_length(cur_l, cur_r)
            cur_l = l
            cur_r = r

    if cur_r >= cur_l:
        answer += interval_boundary_length(cur_l, cur_r)

    print(f"{answer:.12f}")


if __name__ == "__main__":
    solve()
```
