Official

D - 魚捕り / Catching Fish Editorial by admin Editorial for printing

Gemini 3.0 Flash (High)

Overview

This problem asks for the maximum number of points (fish) on a 2D plane that can be enclosed by a rectangle (net) of a fixed size \(W \times H\).

Analysis

1. Restricting the Position of the Net

Although the net can be placed at any real-valued coordinates, if we want to maximize the number of fish inside the net, it is sufficient to consider only cases where the \(x\)-coordinate of the net’s left edge and the \(y\)-coordinate of the net’s bottom edge each coincide with the coordinates of some fish. This is because shifting the net slightly while it contains fish does not change the count of caught fish as long as no fish crosses the net’s boundary.

2. Considering One Dimension at a Time (Sweep Line)

First, let us consider the \(x\)-axis direction. If \(a\) is the \(x\)-coordinate of the net’s left edge, the fish that can be caught are those satisfying \(a \leq X_i \leq a + W\). When fixing the set of fish contained within this \(x\)-range, the next subproblem along the \(y\)-axis is to determine at which height \(b\) to place the net so that the region \(b \leq Y_i \leq b + H\) contains the maximum number of fish.

3. Reformulating the \(y\)-axis Condition as an Interval

The condition for fish \(i\) to be within the net’s \(y\)-range is \(b \leq Y_i \leq b + H\). Rewriting this as a condition on the net’s bottom edge \(b\), we get: $\(Y_i - H \leq b \leq Y_i\)\( In other words, setting the bottom edge \)b\( of the net within this range allows us to catch fish \)i\(. By considering this "possible range for \)b\(" for each fish and finding **the point where the maximum number of ranges overlap**, we obtain the maximum value for that \)x$-range.

4. Sliding Window and Data Structures

As we move the net along the \(x\)-axis (sliding window), we dynamically maintain the overlaps along the \(y\)-axis. 1. Sort the fish in ascending order of their \(X\)-coordinates. 2. Sequentially add fish entering the net’s \(x\)-range and remove fish leaving the range. 3. When fish \(i\) enters the \(x\)-range, add \(+1\) to the interval \([Y_i - H, Y_i]\). 4. When fish \(i\) leaves the \(x\)-range, subtract \(1\) from the interval \([Y_i - H, Y_i]\). 5. If we can always query the “maximum value across all intervals” quickly, we can find the answer.

Since the coordinate values can be large, we can solve this efficiently by coordinate compressing the occurring \(Y\)-coordinates and using a lazy segment tree that supports range additions and range maximum queries.

Algorithm

  1. Sort the fish by \(X_i\).
  2. Coordinate compress all occurring \(Y_i\) and map them to segment tree indices.
  3. Maintain two pointers left and right (sliding window).
  4. As right advances, add \(+1\) to the segment tree range corresponding to the new fish’s \(y\)-range \([Y_i - H, Y_i]\).
  5. When fish[right].X - fish[left].X > W, remove the fish at left and subtract \(1\) from its \(y\)-range.
  6. At each step, record the overall maximum value in the segment tree; the maximum among them is the final answer.

Complexity

  • Coordinate compression and sorting: \(O(N \log N)\)
  • Sliding window (\(N\) additions and deletions): \(O(N \log N)\)
    • Each segment tree operation (addition / maximum query) takes \(O(\log N)\)
  • Time Complexity: \(O(N \log N)\)
  • Space Complexity: \(O(N)\)

Implementation Notes

  • Target of Coordinate Compression: Candidates for the net’s bottom edge \(b\) include not only \(Y_i\) but also \(Y_i - H\). However, in this implementation, only \(Y_i\) are used as the base points for coordinate compression, and bisect_left is used to find which position corresponds to \(Y_i - H\).

  • Lazy Segment Tree: Since range addition and range maximum query are required, a Lazy Segment Tree is used. In Python, recursive implementations tend to be slow, so an iterative (non-recursive) implementation is preferred.

    Source Code

import sys
import bisect

class LazySegmentTree:
    """
    Range Add, Global Max Segment Tree
    Complexity: O(log N) for add, O(1) for query
    """
    def __init__(self, data_size):
        # Smallest power of 2 greater than or equal to data_size
        self.n = 1 << (data_size - 1).bit_length()
        self.tree = [0] * (2 * self.n)
        self.lazy = [0] * (2 * self.n)

    def add(self, l, r, val):
        """Adds val to the range [l, r] (inclusive)"""
        if l > r:
            return
        l += self.n
        r += self.n
        l0, r0 = l, r
        
        # Iterative range addition
        while l <= r:
            if l & 1:
                self.tree[l] += val
                self.lazy[l] += val
                l += 1
            if not (r & 1):
                self.tree[r] += val
                self.lazy[r] += val
                r -= 1
            l >>= 1
            r >>= 1
        
        # Update ancestors of the modified range boundaries
        l0 >>= 1
        while l0:
            lc = self.tree[l0 << 1]
            rc = self.tree[l0 << 1 | 1]
            self.tree[l0] = (lc if lc > rc else rc) + self.lazy[l0]
            l0 >>= 1
        r0 >>= 1
        while r0:
            lc = self.tree[r0 << 1]
            rc = self.tree[r0 << 1 | 1]
            self.tree[r0] = (lc if lc > rc else rc) + self.lazy[r0]
            r0 >>= 1

    def query(self):
        """Returns the global maximum value in the tree"""
        return self.tree[1]

def solve():
    # Read all input at once for speed
    input_data = sys.stdin.read().split()
    if not input_data:
        return
    
    N = int(input_data[0])
    W = int(input_data[1])
    H = int(input_data[2])
    
    fish = []
    Y_vals = []
    idx = 3
    for _ in range(N):
        x = int(input_data[idx])
        y = int(input_data[idx+1])
        fish.append((x, y))
        Y_vals.append(y)
        idx += 2
        
    # Step 1: Sort fish by X-coordinate to facilitate the sliding window
    fish.sort()
    
    # Step 2: Coordinate compression for Y-coordinates
    # Any optimal window bottom edge can be assumed to be at a fish's Y-coordinate.
    U = sorted(list(set(Y_vals)))
    val_to_idx = {v: i for i, v in enumerate(U)}
    M = len(U)
    
    # Pre-calculate the range of indices in U that each fish covers.
    # A fish at Y_j is caught by a net with bottom edge b if b <= Y_j <= b + H,
    # which is equivalent to Y_j - H <= b <= Y_j.
    fish_y_ranges = []
    for i in range(N):
        fy = fish[i][1]
        idx_l = bisect.bisect_left(U, fy - H)
        idx_r = val_to_idx[fy]
        fish_y_ranges.append((idx_l, idx_r))
    
    # Step 3: Sliding window on X-coordinates
    st = LazySegmentTree(M)
    ans = 0
    right = 0
    for left in range(N):
        # Move the right boundary of the window as far as possible
        x_left_limit = fish[left][0] + W
        while right < N and fish[right][0] <= x_left_limit:
            idx_l, idx_r = fish_y_ranges[right]
            st.add(idx_l, idx_r, 1)
            right += 1
        
        # Query the maximum number of fish in the current X-window across all Y-windows
        res = st.query()
        if res > ans:
            ans = res
        
        # Remove the leftmost fish as the left boundary of the window moves
        idx_l, idx_r = fish_y_ranges[left]
        st.add(idx_l, idx_r, -1)
        
    # Output the maximum number of fish found
    print(ans)

if __name__ == '__main__':
    solve()

This editorial was generated by gemini-3-flash-high.

posted:
last update: