We are to maximize the expected number of fishes caught when the scoop is placed uniformly at random over all possible positions (n - r + 1)*(m - r + 1). The expected number = sum over fishes of probability that a given fish is caught, by linearity of expectation. Since fishes are independent placements, the expected number = sum_{i=1 to k} p_i where p_i is probability that a random scoop position covers the cell of fish i. The probabilities depend only on the cell's coordinates, not on other fishes. So we want to choose k distinct cells that maximize sum of probabilities. Hence the solution: compute for each cell (i, j) in the n x m grid the probability that a random r x r scoop (with lower-left corner in valid positions) covers that cell. Then select the k cells with highest probabilities, sum them. Then output that sum (as double). However, careful: The expected value of number caught is the average over random scoop placements of sum of indicator variables for each fish. That sum of probabilities is indeed the expected value, because linearity holds regardless of dependence. So we need to compute p(i, j) for all cells. Since n,m up to 1e5, total cells up to 1e10, cannot iterate all. But k ≤ 1e5, so we only need the top k probabilities. The probability for cell (x, y) (I'll use 1-indexed coordinates) is: number of scoop positions that cover (x,y) divided by total number of positions.
Let’s derive coverage count. The scoop is r x r with lower-left corner (a,b) where 1 ≤ a ≤ n - r + 1, 1 ≤ b ≤ m - r + 1 (if using 1-index). The scoop covers cells with coordinates (i,j) such that a ≤ i ≤ a + r - 1, b ≤ j ≤ b + r - 1. For a given cell (x,y), it is covered if a ∈ [x - r + 1, x] ∩ [1, n - r + 1] and b ∈ [y - r + 1, y] ∩ [1, m - r + 1]. The length of valid a range is: min(x, n - r + 1) - max(1, x - r + 1) + 1 if that's positive, else 0. Similarly for b. Since the scoop positions are uniformly random over all (n - r + 1)*(m - r + 1) positions, p(x,y) = (horizontal_choices * vertical_choices) / total_positions.
Alternatively, we can compute coverage count as: number of placements such that the scoop's lower-left corner lies within a specific range. Equivalent to: the number of a positions = the number of integer a such that max(1, x - r + 1) ≤ a ≤ min(x, n - r + 1). So width = min(x, n - r + 1) - max(1, x - r + 1) + 1. Similarly for y.
We need to compute p(i,j) quickly for many cells. Observations: p(i,j) = f(i)*g(j) / total, where f(i) = number of a positions covering row i, and g(j) = number of b positions covering column j, because the placements in rows and columns are independent: the number of placements covering (i,j) is f(i)g(j). Indeed: the set of a positions depends only on i, and b positions only on j. So p(i,j) = (f(i) * g(j)) / T, where T = (n - r + 1)(m - r + 1). So probability is product of row factor and column factor (up to scaling). So to maximize sum of probabilities of selected cells, we need to choose k cells with largest f(i)*g(j). Since f(i) and g(j) are nonnegative integers (0? Actually f(i) is positive for cells that can be covered; but maybe some cells near edges have fewer placements. But all cells have at least 1? If r ≤ n,m, and r>=1, then for any cell, there is at least one placement? Let's check: cell at (1,1) is covered if lower-left corner at a=1, b=1; also a could be 1 only? Actually a ∈ [max(1, 1 - r + 1)=1, min(1, n - r + 1)=min(1, ...). If n - r + 1 >= 1 then min = 1, so only a=1. So f(1)=1. Similarly, for cell at (n, m) a ∈ [max(1, n - r + 1), min(n, n - r + 1)] = [n - r + 1, n - r + 1] = 1. So yes, all cells have at least one placement because r ≤ n,m, but if n - r + 1 might be less than 1? Actually n >= r => n - r + 1 >= 1. So it's always at least 1. So f(i) >=1, g(j) >=1. So product positive.
Thus we need to choose k distinct pairs (i,j) maximizing f(i)g(j). Since f(i) depends only on i and g(j) only on j, and we can choose any combination, we need to select the k highest products from the Cartesian product of row values and column values. However, there is constraint that we cannot choose the same cell twice (i.e., same pair (i,j) multiple times). But since each (i,j) corresponds to a distinct cell, we just need top k products among all pairs. However note that f(i) and g(j) may not be distinct for different i/j; but the products will be many. So the problem reduces to: given two multisets A = {f(i) for i=1..n} and B = {g(j) for j=1..m}, compute sum of top k values from the multiset {ab : a in A, b in B}, divided by T. But note: Since the grid cells correspond to all pairs (i,j), there are n*m products, but we need only the top k. k ≤ 1e5, so we can efficiently get top k products using a priority queue (max-heap) technique, similar to "k maximum sum combinations" problem where given two arrays, we need largest k sums/products. However careful: We are dealing with products, not sums. But the typical approach for sum: sort descending, use heap of pairs indices (i,j) with next possibilities. For product, it's similar but we need to handle multiplicities? However, since the arrays A and B can be large (up to 1e5 each), but n,m up to 1e5, so total size of A and B is up to 1e5 each, but product set is huge. But k is only up to 1e5, so we can generate top k products efficiently by using a max-heap over candidates. Approach: Compute all f(i) values for rows (size n). Compute all g(j) values for columns (size m). Sort both arrays in descending order. Then, the maximum product is max(A)*max(B). Next candidates are from combinations like (next row with same column) etc. We need to ensure we don't duplicate the same cell. However, note that the product value can be achieved by multiple (i,j) pairs if there are ties (same f(i) values for different rows and same g(j) for different columns). But the cells are distinct. So when we output the sum of probabilities, we need to sum the actual probabilities for each cell we select. But if two cells have the same product, they contribute the same probability. But we may need to take many of them if k is large.
Thus we need to compute the sum of the top k values in the multiset S = { a_i * b_j } where a_i = f(i), b_j = g(j). This is classic: given two sorted arrays, find the largest k products. Since k ≤ 1e5, we can use a max-heap that stores (product, i, j) for combinations. But careful: The number of distinct (i,j) pairs is huge. However, the heap approach typically works for sums: we start with (0,0) as the largest sum (since sorted descending) then push neighbors (i+1,j) and (i,j+1) with condition to avoid duplicates. For product, same structure: The set of pairs (i,j) in sorted order by product is not monotonic in i,j like sum because product is not linear; however, if both arrays are sorted descending, then the product matrix is sorted in rows and columns in a certain sense: it's a monotone matrix? Actually, if A and B are sorted descending, then for any i ≤ i' and j ≤ j', we have A[i] * B[j] ≥ A[i'] * B[j] and ≥ A[i] * B[j']. But not necessarily that A[i] * B[j] ≥ A[i'] * B[j']? Actually if i ≤ i' and j ≤ j', then A[i] ≥ A[i'] and B[j] ≥ B[j'], so product A[i]*B[j] ≥ A[i']*B[j']? Yes because both factors are larger or equal, so product is larger or equal. So the matrix is sorted in anti-majorization: the top-left corner (1,1) is maximum, and as you go down or right, product decreases. So it's a monotone decreasing matrix: each row is decreasing (since B sorted), each column decreasing. So we can apply the standard technique for extracting top k from a sorted matrix: use a max-heap with visited set. Start with (0,0) (indices after sorting). Pop, then push (i+1, j) and (i, j+1) if not visited. This works because the matrix is such that if we have visited (i,j), the next candidates are among those with either i+1 or j+1? But we need to ensure that all elements can be reached and no duplicates. This classic method is used for sums of sorted arrays (where A[i]+B[j] matrix is sorted similarly). For product, the same property holds: if A and B are sorted descending, then A[i]+B[j] and A[i]*B[j] both have the property that moving down or right reduces the value. However, is it true that for any (i,j), the next largest unvisited element is among the neighbors (i+1,j) and (i,j+1) given that we have already taken all larger ones? In the sum case, it's proven. For product, the same reasoning holds: because the set of cells that are not yet visited but could be maximum are those that have either i increased or j increased relative to some visited cell. More formally, the set of indices (i,j) such that i and j are at least the current min indices? Actually the typical algorithm: Start with heap containing (0,0). While extracted count < k, pop max (i,j), then push (i+1,j) and (i,j+1) if not already pushed. This yields the k largest sums (or products) in order, because the matrix is sorted row-wise and column-wise and the next candidates after (i,j) are (i+1,j) and (i,j+1). But we need to ensure that we don't miss some combinations where both i and j are larger but not directly adjacent? Suppose we have popped (0,0), (0,1), (1,0). The next largest could be (1,1). But (1,1) will be pushed when both (0,1) and (1,0) are popped? Actually (1,1) would be pushed twice if we push from both. So we need to avoid duplicates by marking visited. The standard approach ensures that (1,1) will be pushed when the first of its predecessors is popped, but we need to ensure that (1,1) becomes available. It does: from (0,1) we push (1,1); from (1,0) we also push (1,1). To avoid duplication, we can mark (i,j) as visited when we push into heap, or when we pop. Usually, we mark when pushing to avoid duplicate pushes. So the algorithm works for any monotone matrix (each row and column sorted). Because if we have visited all cells with i < i0 or j < j0, then the next maximum is among the frontier cells that are the next in each row/col. The frontier is like the set of cells where either i or j is the next index after some visited cell. The heap ensures we explore. So yes, it works.
But caution: There might be many rows and columns, but we only need top k, so heap size up to O(k). So that's fine.
However, we must compute the product values as integers (maybe up to (n - r + 1)*(m - r + 1)? Actually f(i) ≤ n - r + 1? Wait f(i) = number of a positions covering row i. What is maximum? For rows near the middle, it is r. For column similarly. So max f(i) = min(r, n - r + 1? Actually f(i) = min(i, n - r + 1) - max(1, i - r + 1) + 1. Let's compute: For 1 ≤ i ≤ n, f(i) = number of integer a such that a ∈ [max(1, i - r + 1), min(i, n - r + 1)]. The length of that interval is: if i - r + 1 ≤ 1, then lower bound is 1, upper bound is min(i, n - r + 1). Since i ≤ n, min(i, n - r + 1) is i if i ≤ n - r + 1, else n - r + 1. So f(i) = min(i, n - r + 1) - 1 + 1? Actually compute directly: length = min(i, n - r + 1) - max(1, i - r + 1) + 1. This is symmetric: essentially f(i) = min(r, i, n - i + 1? Not exactly. Let's do: f(i) = number of placements covering row i. Equivalent to: the number of starting rows a such that a ≤ i ≤ a + r - 1 => a ∈ [i - r + 1, i]. Then intersect with [1, n - r + 1]. So f(i) = length of intersection = min(i, n - r + 1) - max(1, i - r + 1) + 1. This is positive. For i in [1, n], the maximum value is r (when both intervals fully overlap, i.e., i - r + 1 ≥ 1 and i ≤ n - r + 1 => r ≤ i ≤ n - r + 1. So if r ≤ n - r + 1 => 2r ≤ n+1? Actually n >= r so n - r + 1 >= 1. The condition for maximum r is that [i - r + 1, i] is completely within [1, n - r + 1]. The lower bound i - r + 1 >= 1 => i >= r. The upper bound i <= n - r + 1. So i must satisfy r ≤ i ≤ n - r + 1. If that interval is non-empty, then there exist rows i with f(i)=r. If not, then the maximum f(i) is less than r; it would be min(i, n - i + 1?) Actually for n < 2r? Example: n=5, r=3 => n - r + 1 = 3. For i=3, f(3) = min(3,3) - max(1, 1) + 1 = 3-1+1=3 => r. For i=2: min(2,3)=2, max(1,0)=1 => 2-1+1=2. For i=4: min(4,3)=3, max(1,2)=2 => 3-2+1=2. So max is 3 = r. So condition: n - r + 1 >= r? Actually need existence of i such that i >= r and i <= n - r + 1 => r <= n - r + 1 => 2r <= n+1 => r <= floor((n+1)/2). If r > floor((n+1)/2), then the intervals for i near the edges are overlapping? Example: n=5, r=4 => n - r + 1 = 2. Then i must be between 4 and 2? impossible. So max f(i) is min(r, n - r + 1? Wait compute: f(i) = min(i, n - r + 1) - max(1, i - r + 1) + 1. For i near center, say i=3: min(3,2)=2, max(1,0)=1 => 2-1+1=2. So max =2, which is n - r + 1 =2, because r is larger than half. So indeed max f(i) = min(r, n - r + 1). Similarly for columns. So the max f(i) = min(r, n - r + 1). Similarly max g(j) = min(r, m - r + 1). So product max = min(r, n - r + 1) * min(r, m - r + 1). But note r ≤ n,m, so min(r, n - r + 1) could be either r if r ≤ n - r + 1 (i.e., 2r ≤ n+1), else n - r + 1. So product max maybe r^2 if both dimensions are large enough relative to r. So product values are within about r^2 ≤ (1e5)^2=1e10, fits in 64-bit.
Thus we can compute f(i) for all i=1..n? n up to 1e5, so we can compute all f(i) in O(n). Similarly g(j) in O(m). That's fine.
Then we sort f and g descending: f_sorted descending (largest first), g_sorted descending. We'll work with indices 0..n-1, 0..m-1.
Now we need to extract the top k products. But careful: The products f(i)g(j) correspond to actual cells. However, there may be many pairs (i,j) with the same product. The heap algorithm will generate each product multiple times if there are multiple (i,j) that map to same indices in the sorted arrays? Actually sorted arrays contain values, but each index in sorted arrays corresponds to a specific row (or column) with that f value. However, if we use sorted arrays and treat indices (i_idx, j_idx) as representing the product of the f-value at position i_idx in the sorted list and the g-value at position j_idx, then each (i_idx, j_idx) corresponds to a particular row and column, but careful: if two rows have the same f-value, they appear as separate indices in the sorted array; similarly for columns. Then the combination (i_idx, j_idx) corresponds to a unique row index (original row) and column index (original column). That's exactly one cell. So mapping from sorted indices to original row/col is one-to-one? Actually sorted list is just the multiset of f-values; we need to know which row each value came from. But for the purpose of computing probabilities, we need actual product f(i)g(j) for that cell. However, if we just store the f-value and g-value in the sorted lists, we can compute product. But note: There could be many rows with same f-value; each such row will appear as a distinct entry in the sorted array. So we can treat the sorted arrays as lists of values with associated original IDs if needed? But in the heap algorithm we only need the product values, not the actual row/col IDs, because we just need to sum top k products. However, we must be careful: The sorted arrays f_sorted and g_sorted may have duplicates. The algorithm using indices (i,j) on sorted arrays will generate each combination of a specific row from f_sorted[i] and a specific column from g_sorted[j]. That's exactly the Cartesian product of all rows and columns. So it's fine. But we have to ensure we don't double count the same actual cell when there are duplicate values? Actually each (i,j) corresponds to a unique row and column: the row is the one that originally gave f_sorted[i] (the i-th element in sorted order). But if two rows have the same f-value, they occupy different indices i1 and i2. So (i1, j) and (i2, j) are different cells (since rows differ). So it's fine. However, we must note that the sorting might lose the mapping to original indices but that's okay because we don't need to output which cells, just sum of top k probabilities. So we can treat the sorted arrays as values only, and the heap will produce product values. But we need to ensure we count each cell exactly once. Since we will generate pairs (i,j) where i is index in the sorted f array and j index in sorted g array. But if f_sorted has n elements and g_sorted has m elements, then there are nm distinct pairs (i,j). That exactly corresponds to nm cells, each with product = f_sorted[i] * g_sorted[j]. So we can simulate.
Thus we can use a max-heap containing entries (product, i, j). Initialize with (f_sorted[0]*g_sorted[0], 0, 0). We'll also have a visited set to avoid duplicate pushes. Since n,m up to 1e5, visited set could be large if we store all visited pairs. However we will only push up to O(k) distinct pairs because we only pop k times. But we may push more than k? In typical algorithm, each pop may push up to 2 new entries, so total pushes ≤ 2k + 1. So visited set size is O(k). That's fine. We'll use a hash set or boolean matrix? Better to use a set of pairs (i,j). Since i and j up to 1e5, but we only store at most 2e5 pairs, it's okay.
Now for each pop, we add the product to sum (as double). After k pops, we have sum of top k products. Then expected value = sum / T.
But careful: The products are integers representing the number of scoop placements covering the cell. The probability = product / T. So sum of probabilities = (sum of products) / T. So we can compute sum_products as integer (maybe large, up to k * r^2 ≤ 1e5 * 1e10 = 1e15, fits in 64-bit). Then output sum_products / T as double with high precision.
Thus algorithm:
-
Read n, m, r, k.
-
Compute total positions T = (n - r + 1) * (m - r + 1) as long long.
-
Compute vector f of size n: for i from 1..n: f[i-1] = compute f(i). Similarly g for j.
Compute f(i) as:
low = max(1, i - r + 1)
high = min(i, n - r + 1)
if low <= high: f = high - low + 1 else 0? But should be always >0.
Equivalent: f(i) = min(i, n - r + 1) - max(1, i - r + 1) + 1.
Since all terms are integers, compute directly.
Alternatively, a simpler formula: f(i) = min(r, i, n - i + 1? Not exactly, but we can compute quickly.
Better to compute as:
x = min(i, n - r + 1)
y = max(1, i - r + 1)
f_i = x - y + 1
That works.
Similarly for g: using m.
-
Sort f in descending order, g in descending order. (We can use sort O(n log n) etc; n,m up to 1e5, fine).
-
Use a max-heap (priority queue) where each element is a tuple (product, i, j). Since we want max, we can store product as negative for min-heap? We'll use max-heap via negative or custom comparator. In C++, we can use priority_queue with tuple where product is first and we want largest product, so use default (which is max for first element if we put negative? Actually default is max-heap for pairs? C++ priority_queue is a max-heap by default, but it compares using less, which gives the largest element. So if we store pair<long long, pair<int,int>>, it will order by first (product) descending. So we can push positive product.
-
Initialize visited set as e.g., set of pair<int,int> or unordered_set with hashing. Push (0,0) with product = f[0]*g[0]. Mark visited.
-
Loop for iter = 0..k-1:
- pop top (prod, i, j)
- sum_prod += prod
- consider (i+1, j) if i+1 < n and not visited. push product f[i+1]*g[j], mark visited.
- consider (i, j+1) if j+1 < m and not visited. push product f[i]*g[j+1], mark visited.
-
After loop, expected = (double)sum_prod / T.
-
Output with e.g., printf("%.10lf\n", expected) or set precision.
But careful: The above algorithm is typical for sums, but does it work for products? The property required is that the matrix sorted in both rows and columns (non-increasing) and that the order is such that when we move to (i+1,j) and (i,j+1), we cover the next candidates. But is it guaranteed that after popping (i,j), the next largest product is among (i+1,j) and (i,j+1)? Let's reason.
We have a matrix M[i][j] = f[i]*g[j] with f sorted descending and g sorted descending. So each row is descending (since g is fixed order? Actually g sorted descending, so along row i, as j increases, g[j] decreases, so product decreases. Similarly, each column is descending. So M is a monotone matrix: i1 <= i2 and j1 <= j2 implies M[i1][j1] >= M[i1][j2] and M[i1][j1] >= M[i2][j1] and also M[i1][j1] >= M[i2][j2]? Since both factors are larger or equal, product is larger or equal. So yes, it's monotone decreasing in both dimensions.
Now, consider the set of all pairs (i,j). After extracting the maximum at (0,0), the next maximum could be either (0,1) or (1,0). That is true because if there were some (i,j) with i>0 and j>0 that is larger than both (0,1) and (1,0), then M[i][j] > M[0][1] and > M[1][0]. Since M[0][1] = f[0]*g[1] and M[1][0] = f[1]*g[0]. If i>0 and j>0, then f[i] ≤ f[0] and g[j] ≤ g[0]; but could f[i]*g[j] exceed f[0]*g[1]? Suppose f[0] is much larger than f[1], and g[1] is small; then maybe f[1]*g[0] could be larger than f[0]*g[1]? But we already have (1,0) considered. Could there be (1,1) larger than (0,1) and (1,0)? Since f[1] ≤ f[0] and g[1] ≤ g[0], we have f[1]*g[1] ≤ f[0]*g[1] and ≤ f[1]*g[0]. So (1,1) cannot be larger than both (0,1) and (1,0). So indeed the next maximum after (0,0) is among (0,1) and (1,0). Now by induction, the typical algorithm works: The set of visited cells forms a Young diagram shape: if we have visited all cells (i,j) with i+j < s? Actually not exactly, but the algorithm maintains that whenever a cell (i,j) is popped, its "right" and "down" neighbors become candidates because any cell that is not yet visited and not yet considered must be reachable via a path of increments from some visited cell, and the largest among unvisited will be on the frontier of visited cells. More formal proof: The set of unvisited cells that are not yet in heap but might be the next maximum are those that have all their "up" or "left" neighbors visited? Actually typical algorithm for sorted matrix works for any matrix where rows and columns are sorted (monotone). It uses the property that if we have already inserted (i,j) into heap, then before extracting it, we know that all cells with smaller i and j are already extracted (or in heap). So after extracting (i,j), we consider adding (i+1,j) and (i,j+1) because they are the smallest indices that are not yet considered but could be next. It's a known technique for "k smallest sums" etc. It works for both sums and products because both preserve the sorted order. So we can adopt.
But caution: The algorithm as described will generate each cell at most once. However, we must also consider that when we push (i+1,j) and (i,j+1), there might be duplication if they have already been pushed from other predecessors. We'll use visited set to avoid duplicate pushes.
Thus algorithm yields the k largest products.
Now check with examples.
Example 1:
n=3,m=3,r=2,k=3.
Compute f(i) for rows: n=3,r=2 => n-r+1=2.
i=1: min(1,2)=1, max(1,0)=1 => 1-1+1=1.
i=2: min(2,2)=2, max(1,1)=1 =>2-1+1=2.
i=3: min(3,2)=2, max(1,2)=2 =>2-2+1=1.
So f = [1,2,1] sorted descending => [2,1,1].
Similarly g: same => [2,1,1].
Products top 3: (22)=4, (21)=2, (21)=2? Actually there are two (2,1) combos: f[0]=2 with g[1]=1 gives 2; f[0] with g[2]=1 gives 2; also f[1]=1 with g[0]=2 gives 2; but we need only 3 cells, so we can take 4,2,2. Sum products = 8. T = (3-2+1)(3-2+1) = 2*2=4. Expected = 8/4 = 2.0. matches.
Our algorithm: sorted f=[2,1,1], g=[2,1,1]. heap start (4,0,0). pop 4, sum=4, push (i+1,j): (1,0): f[1]g[0] = 12 =2; (i,j+1): (0,1): f[0]g[1]=21=2. Mark visited. Next pop max of {2,2} say (2,0,1). sum=6. From (0,1) push (1,1): f[1]g[1]=11=1 and (0,2): f[0]g[2]=21=2? Actually (0,2) product = 2*1=2. But careful: j+1=2, so (0,2) product 2. Also from (0,1) we push (1,1) and (0,2). Now visited: (0,0),(0,1),(1,0). When we push (1,1) and (0,2), we mark visited. Next pop: the heap contains maybe (2,1,0) from earlier? Actually after first pop we had (2,1,0) and (2,0,1). If we popped (2,0,1) second, then heap now has (2,1,0) and also after second pop we push (1,1) and (0,2). Now (2,1,0) product 2, (1,1) product 1, (0,2) product 2. So heap max is 2 (either (2,1,0) or (0,2)). Pop one of them, say (2,1,0). sum=8. That's three pops, sum=8. Good. So algorithm works.
Example 2:
n=12,m=17,r=9,k=40. We'll test later.
Now potential issues: The heap method may generate more than k pushes but still O(k). However, we need to be careful: There might be many cells with same product values, and the algorithm might need to consider many cells beyond k if the product values plateau. But we only need the sum of top k, so after k pops we stop. But we must ensure that the heap algorithm indeed yields the top k in order, not skipping any. As argued, it's correct for any matrix with rows and columns sorted in non-increasing order. But there is a nuance: For the "k maximum sum combinations" problem, the algorithm works because the arrays are sorted and we consider (i+1,j) and (i,j+1). That's standard. For product, same.
But we must also verify that the condition for pushing (i+1,j) and (i,j+1) is sufficient: Suppose we have popped (i,j). Could the next maximum be (i+1, j+1) without having (i+1,j) or (i,j+1) in the heap? If both (i+1,j) and (i,j+1) are still in heap (or yet to be pushed) and they are larger than (i+1,j+1), then (i+1,j+1) won't be candidate until those are popped. But is it possible that (i+1,j+1) is larger than (i+1,j) or (i,j+1)? Since f[i+1] ≤ f[i] and g[j+1] ≤ g[j], we have:
M[i+1][j] = f[i+1]*g[j] ≥ f[i+1]*g[j+1] = M[i+1][j+1]? Actually g[j] ≥ g[j+1] so M[i+1][j] ≥ M[i+1][j+1].
Similarly M[i][j+1] ≥ M[i+1][j+1].
Thus M[i+1][j+1] is not larger than both M[i+1][j] and M[i][j+1]; it is less than or equal to both. So it cannot be the next maximum if those are still unpopped, because those are larger. So it's safe to only push direct neighbors.
Thus algorithm is valid.
Now complexity: sorting O(n log n + m log m). Heap operations O(k log k). Good.
But we must consider that n or m might be up to 1e5, and k up to 1e5, so it's fine.
Edge Cases:
-
r = 1: then f(i)=1 for all i, g(j)=1 for all j. So all products = 1. Top k sum = k. T = nm. Expected = k/(nm). So any placement yields same expected. Our algorithm will compute f all 1, g all 1. Sorted descending: all 1. Then heap algorithm will produce top k products of 1. Works.
-
r = n (or m). Suppose r = n ≤ m. Then scoop width is n rows. Then f(i): compute. Since n - r + 1 = n - n + 1 = 1. So f(i) = min(i, 1) - max(1, i - n + 1) + 1. Since n large? Actually i - n + 1 ≤ i? For i = 1: min=1, max(1,1-n+1)=max(1, -n+2)=1 => 1-1+1=1. For i = n: min(n,1)=1, max(1, n-n+1)=max(1,1)=1 => 1-1+1=1. So f(i)=1 for all i. So all rows have f=1. g(j) = min(j, m - n + 1) - max(1, j - n + 1) + 1? Actually r=n, so g(j) uses m: m - r + 1 = m - n + 1. So g(j) values may vary from 1 up to min(n, m - n + 1?) Actually maximum is min(r, m - r + 1) = min(n, m - n + 1). So if m is large, some columns have larger g. So products = g(j). So to maximize sum, we pick k cells with largest g values. But note that each row has f=1, so product = g(j). However, each column j can provide n cells (since any row). But we only need k cells, we can pick the columns with highest g first, using as many rows as needed. Since all rows have same f, it's essentially pick the top k values from repeated g across rows. But the product matrix is: for each row i (f_i=1) and column j (g_j), product = g_j. So there are n copies of each g_j. So the top k products will be the k largest values among g_j repeated n times. So sum = sum of top k g-values (with multiplicities up to n). Our algorithm will generate sorted f = [1,1,...,1] descending, sorted g descending. Then heap will produce products: initially (1g[0],0,0)=g[0]. Then from (0,0) push (1,0) and (0,1). (1,0) product = 1g[0]=g[0]; (0,1) product = 1*g[1]=g[1]. Then subsequent pops will produce the next highest g values. However, note that there are n rows, so the top products are: g[0] appears n times (for each row i with column 0). But will the heap generate all n copies? Let's simulate: n=3, m=5, r=n=3 => f=[1,1,1], g say [5,4,3,2,1] (just illustrative). Sorted f = [1,1,1] (all equal). Sorted g descending: [5,4,3,2,1].
We need top k= maybe 5 products. The largest product is 5 (row0 col0). Next largest are also 5 from row1 col0 and row2 col0? Actually all rows yield product 5 with column 0. So top 3 products are 5,5,5. Then next is 4 from any row with column1. So we need to get three 5's. Our heap algorithm:
Initialize with (0,0) product=5.
Pop (5,0,0): push (1,0) product=5 and (0,1) product=4.
Visited: (0,0). Now heap: (5,1,0), (4,0,1).
Pop (5,1,0): push (2,0) product=5 and (1,1) product=4. Mark (1,0),(2,0),(1,1)? Actually we push (2,0) and (1,1) if not visited. visited currently: (0,0), (1,0). So (2,0) not visited -> push; (1,1) not visited -> push. Now heap: (4,0,1), (5,2,0), (4,1,1). Possibly also (4,0,1) still there.
Pop next max: that is (5,2,0). sum third = 5. Now we have three 5's. Good. So algorithm will produce all n copies of g[0] before moving to g[1] because each time we pop a cell (i,0) we push (i+1,0) until i reaches n-1. So indeed we get all rows for column 0 before column 1 appears? But note: also (0,1) was pushed early, but its product 4 is less than 5, so it stays in heap. So we correctly get all rows for col0. So algorithm works.
Now consider r large but not exactly n, e.g., n=5,r=4 => f(i) values: compute: n - r + 1 =2. For i=1: min(1,2)=1, max(1, -2)=1 ->1; i=2: min(2,2)=2, max(1,-1)=1 ->1; i=3: min(3,2)=2, max(1,0)=1 ->1; i=4: min(4,2)=2, max(1,1)=1 ->1; i=5: min(5,2)=2, max(1,2)=2 ->1? Wait compute: i=5: min(5,2)=2, max(1,5-4+1=2)=2 => 2-2+1=1. So all f(i)=1? Let's recalc properly: n=5, r=4 => n-r+1=2. For i=1: low=max(1,1-4+1=-2)=1, high=min(1,2)=1 =>1. i=2: low=max(1,2-4+1=-1)=1, high=min(2,2)=2 =>2-1+1=2? Actually high=2, low=1 =>2-1+1=2. Wait I miscalc: For i=2, high = min(i, n-r+1) = min(2,2) = 2; low = max(1, i-r+1) = max(1, 2-4+1=-1) = 1; so f=2-1+1=2. So i=2 has f=2. i=3: high = min(3,2)=2; low = max(1, 3-4+1=0)=1; f=2-1+1=2. i=4: high = min(4,2)=2; low = max(1,4-4+1=1)=1; f=2-1+1=2. i=5: high = min(5,2)=2; low = max(1,5-4+1=2)=2; f=2-2+1=1. So f = [1,2,2,2,1]. So not all ones. So it's fine.
Now algorithm robust.
Now note: k is up to min(nm, 1e5). So if k is large, we might need to process many cells. But since k ≤ 1e5, our heap algorithm will do at most k iterations. However, if nm is less than k? Actually k ≤ nm, but nm could be as large as 1e10, but k is only 1e5, so fine.
But we must be cautious about memory: storing f and g arrays of size up to 1e5 each is fine.
Now about sorting: We sort f and g descending. However, is it necessary? Perhaps we could generate top k products without sorting entire arrays? Since n,m up to 1e5, sorting is okay.
But we should consider that f(i) can be computed quickly. Actually we can compute f(i) distribution directly without enumerating all i if n is huge? But n up to 1e5, enumeration fine.
Now, we must confirm that the product values f(i)*g(j) correspond exactly to the number of scoop placements covering the cell. Yes: number of placements = f(i)*g(j). So sum of these over selected cells = total expected fish count * T.
Now potential pitfalls: The heap algorithm described works for extracting the k largest elements from a matrix where rows and columns are sorted descending. However, we must ensure we push only valid indices (i+1 < n) etc. Also we need visited tracking. Since we only push O(k) entries, we can use unordered_set with a custom hash for pair<int,int> or a set of long long (combine im+j, but m might be up to 1e5, so i1e5 + j fits in 1e10, still within 64-bit, but we can just use set of pair. For up to 2e5 entries, it's fine.
Alternatively, we could avoid visited set by using a boolean matrix of visited? But n and m up to 1e5, cannot allocate n*m. So use unordered_set.
But we can also avoid visited set by using the property that each cell is pushed only once if we push only when i==0 or j==0? Actually there is known optimization: For k maximum sums from two arrays, one can push (i+1, j) only when j==0, etc. But that's for sums where arrays sorted ascending? There is typical solution where you sort both arrays, then push all (i,0) for i=0..n-1, then each time pop (i,j) and push (i,j+1). That works because the sums are monotone in j for fixed i? For sums, if we fix i, sums a[i]+b[j] increase as j increases if b is sorted ascending? Actually if we have both sorted descending, then for fixed i, a[i] is constant, b[j] decreasing, so sum decreasing with j. So the largest sum is a[0]+b[0], then next could be a[0]+b[1] or a[1]+b[0]. But the alternative algorithm: push all (i,0) into heap, then each time pop (i,j), then push (i,j+1). This yields the k largest sums because for each i, the sequence (i,j) is decreasing, and we need to consider each i's progression. But that works because the heap initially contains the maximum for each row (i,0). Then when we pop the global max, we replace it with the next element in that row. This algorithm does not require visited set and works for sums. However, for product, the same idea should work: since for fixed i, product a[i]*b[j] decreases as j increases (b descending). So we can use this alternative algorithm: sort both descending. For each i from 0 to n-1, push (product = a[i]*b[0], i, 0) into heap. Then for k times: pop top (prod, i, j), add to sum, then if j+1 < m, push (a[i]*b[j+1], i, j+1). That's simpler and avoids visited set. Is it correct? Let's test: The initial heap contains the maximum product for each row: (i,0). The global max is among these. After popping the global max (say from row i0), the next candidate for row i0 is (i0,1). Meanwhile, other rows still have their current (i, j_i) in the heap. The next largest product overall will be the max among all rows' current (i, j_i). This is correct because the rows are independent and each row's sequence is decreasing. Indeed, for any row i, the products are in descending order as j increases. So if we always maintain for each row the next unpopped column index, the global max among those front elements will be the next overall maximum product. This is analogous to merging k sorted lists: each row i gives a sorted (descending) list of products a[i]*b[j] for j=0..m-1. We want the k largest across all rows. So we can treat each row as a list and use a heap to merge them. Since n can be up to 1e5 and we only need k up to 1e5, we could even initialize heap with all rows (i,0). But that would push n elements initially, which could be up to 1e5. That's fine. Then we pop k times. Each pop may push one new element (j+1). Total operations O((n + k) log n). Since n up to 1e5, that's fine. This approach is simpler, no visited set, and clearly correct. However, note that the product lists for each row are not necessarily "lists" we need to generate entirely; we just need to generate the top k across all rows. This merging of sorted lists using a heap works because for each row i, the products a[i]b[j] are sorted descending in j. So we can treat each row as a sorted list. Then the problem reduces to finding the k largest elements among n sorted lists (each of length m). But we don't want to push all nm; we only need k. So we can push the head of each list (j=0) into a max-heap. Then repeatedly pop the largest, and if there is a next element in that row (j+1), push it. This is exactly the standard merge of sorted lists.
But careful: This merging algorithm works when we have n lists each sorted descending. However, we need to ensure that the lists are indeed sorted descending. Since b is sorted descending, for fixed a[i] (positive), a[i]*b[j] is descending as j increases because b[j] decreases. So yes.
Thus we can adopt this method.
But note: n could be as large as 1e5, so initial heap size n could be 1e5. That's okay. k also up to 1e5, so total pushes up to n + k (since each pop may push one more). So overall operations O((n + k) log n). That's fine.
But is there any downside? The heap will contain at most n elements at any time (since each row contributes at most one candidate). That's good.
Thus we don't need the more complicated (i+1,j) and (i,j+1) method; we can do the straightforward merge of lists. However, is there any issue with duplicate values? No, each cell is unique.
Thus algorithm:
-
Compute f[i] for i=1..n, store as vector f (since product may be up to ~1e10, but f up to 1e5, so int is fine? f(i) ≤ r ≤ 1e5, so fits in int, but for product we need long long. So use long long for product, but f values can be int.
-
Compute g[j] similarly.
-
Sort f descending. Actually we need rows sorted? Wait: For the merging approach, we treat each row i (original row index) as having a list of products f[i] * g[j] where g sorted descending. But if we don't sort f descending, the rows might not be in any order. However, the merging algorithm doesn't require the rows themselves to be sorted; each row's list is sorted by j (since g sorted descending). The heap will take care of ordering across rows. So we do not need to sort f. But we need to have the f values for each row. However, the product for row i, column j is f[i] * g[j]. But we can pre-sort g descending to ensure that within each row, the products are descending as j increases. So we should sort g descending. But do we need to sort f? Not necessarily. However, we might want to sort f as well to maybe reduce initial heap size? But we still have to consider all rows initially. Since we must consider all rows, initial heap will have n entries, regardless of sorting f. That's okay.
But careful: The grid cells correspond to all pairs (i,j) where i from 1..n, j from 1..m. If we sort g descending, we are reordering columns; but the product for a given row i and column index j (after sorting) corresponds to the product of f[i] and the j-th largest g value. However, that j-th largest g value could correspond to any original column; but that's fine because we are just enumerating products; each distinct pair (i, j_sorted) corresponds to a distinct cell: the row i and the column that gave that g value. But if multiple columns have the same g value, sorting will assign an order arbitrarily; but each column is distinct, and the product f[i]*g_value is same for those columns if f[i] same? Actually if two columns have same g value, they are different cells, but their product values are equal. When we sort g descending, we have the values in order but we need to treat each column as a separate list element? In the merging approach, each row i should have m products, each corresponding to a distinct column. If we sort g descending, we are effectively reordering the columns; but for each row, the products for each column are just f[i] multiplied by the respective g value. However, after sorting g, the list for row i would be: f[i] * g_sorted[0], f[i] * g_sorted[1], ..., f[i] * g_sorted[m-1]. This list is descending because g_sorted is descending. But are we missing any cells? No, because each original column appears exactly once in that list (its g value appears at some position). However, if we only use g_sorted values, we lose the association with the original column index. But that's okay because we don't need to output which cells, just the sum of products. And each product f[i]*g_orig(j) appears exactly once for each pair (i,j). Since we are iterating over all rows i and over all positions in g_sorted (which is a permutation of original columns), we will generate each product exactly once. However, we must ensure we don't double count or miss columns. In the merging algorithm, we treat each row i as having a list of length m, where the j-th element is f[i] * g_sorted[j]. But that corresponds to mapping original columns to positions j based on sorting. Since each original column appears exactly once in the sorted order, each product f[i]*g_orig(col) appears exactly once in some position j for row i. So summing over all rows i and all j gives the complete set of products. So it's valid.
Thus we can:
-
Compute f array (size n) (not sorted).
-
Compute g array (size m) and sort it descending (or we could keep original and later sort? Actually we need g sorted for the lists to be descending. But we also need to know which columns have been used? No, we just need the values. So we can sort g descending.
-
Now we have n rows, each row has a list of m products f[i] * g_sorted[j] where g_sorted is descending.
-
We want the k largest across all rows.
We can use a max-heap where each entry is (product, row_index, col_index) where col_index is the index in g_sorted (starting from 0). Initially, for each row i (0..n-1), we push (f[i] * g_sorted[0], i, 0). Since there are n rows, push n entries. However, if n is 1e5 and we push all, that's okay. But careful: n could be 100k, m could be 100k, but we only push n entries initially. That's fine.
Then we pop k times. On each pop (product, i, j):
sum += product.
if j+1 < m: push (f[i] * g_sorted[j+1], i, j+1).
This yields the k largest products because for each row, we are generating products in decreasing order. The heap always contains the next unused element from each row that hasn't been popped yet (the current head of that row's remaining list). This is exactly like merging n sorted lists.
Proof: Standard.
Complexities: O(n log n) for sorting g (but we also might sort f? Not needed). O(n) for computing f and g. O(n) for initial heap building (we can push each in O(log n) individually, total O(n log n)). Then O(k log n) for pops and pushes. So total O((n + k) log n + m log m). Since n,m up to 1e5, fine.
But we need to compute g sorted descending; we also need to compute f, but f doesn't need sorting.
Potential memory: storing f (n) and g_sorted (m). Also heap with up to n entries.
Now let's test with example 1: n=3,m=3,r=2 => f = [1,2,1] (order: row1=1, row2=2, row3=1). g original: [1,2,1] (col1=1, col2=2, col3=1). Sorting g descending: [2,1,1]. Now initial heap:
row0 (i=0): f[0]=1 * 2 = 2, (0,0)
row1: f[1]=2 * 2 = 4, (1,0)
row2: f[2]=1 * 2 = 2, (2,0)
Heap: (4,1,0), (2,0,0), (2,2,0)
Pop (4,1,0): sum=4; push next from row1: j=1 product=21=2 (1,1)
Heap now: (2,0,0), (2,2,0), (2,1,1)
Pop one of the 2s: say (2,0,0): sum=6; push next from row0: j=1 product=11=1 (0,1)
Heap: (2,2,0), (2,1,1), (1,0,1)
Pop (2,2,0): sum=8; push (2,2,1): product=1*1=1 (2,1)
Now we have popped 3 times, sum=8, matches. Good.
Now example 2: we can test manually later.
But there is nuance: In this merging method, we are considering rows in original order. But does it guarantee we get the absolute top k products? Since each row's list is sorted descending, the largest elements across rows are indeed the maximum of the heads. So yes.
Potential issue: The number of rows n could be 100000, and we push all n initially. That's okay. However, if k is small (like 1), we still push n entries. But that's acceptable.
But maybe we can reduce initial heap size by sorting f descending and only pushing rows that could possibly be among top k. Because if f is small, its products with g may never be among top k if many rows with larger f exist. However, with n=100k and k=100k, pushing all is fine. So we can keep simple.
Nevertheless, consider the worst-case: n=100000, m=100000, k=100000. Sorting g is O(m log m) = 1e5 log 1e5, okay. Pushing n=1e5 into heap O(1e5 log 1e5) ~ 1e6 operations, fine. Then we do 1e5 pops and pushes => 2e5 heap ops, also fine.
Now about precision: Expected value = sum_products / T. sum_products up to about 1e15, T up to about (1e5)^2 = 1e10. So division yields up to 1e5, well within double precision (53 bits ~ 9e15 integer exactly). So double is fine.
But we must ensure we compute sum_products as long long (64-bit). f and g up to 1e5, product up to 1e10, sum up to 1e15, fits in signed 64-bit (max ~9e18). So use long long.
Now confirm the formula for f(i) and g(j). Let's derive simpler formulas.
Let A = n - r + 1 (number of possible starting rows)
Let B = m - r + 1 (starting columns)
For a given cell (x, y), the number of starting positions covering it is:
X = number of a such that max(1, x - r + 1) ≤ a ≤ min(x, A)
Y = number of b such that max(1, y - r + 1) ≤ b ≤ min(y, B)
Alternatively, we can compute f(x) = min(x, A) - max(1, x - r + 1) + 1.
Simplify: This is basically the number of positions of an r-length interval that can be placed within [1, n] covering point x. It is equivalent to: the length of overlap of intervals [1, A] and [x - r + 1, x]. The length is:
left = max(1, x - r + 1)
right = min(x, A)
if left <= right: right - left + 1 else 0.
We can also think: f(x) = min(r, x, A, n - x + 1? Actually symmetric: The number of starting positions covering x is min(x, A) - (x - r + 1) if x - r + 1 >= 1? Not simpler. Better to compute directly.
Since n up to 1e5, we can just loop and compute.
We must be careful with indexing: Usually we use 1-index for formulas. Implementation: for i from 1 to n:
left = max(1, i - r + 1)
right = min(i, n - r + 1)
f[i-1] = right - left + 1
Similarly for j.
Now consider if n - r + 1 might be zero? But r ≤ n, so n - r + 1 ≥ 1. So it's fine.
Now test with example 2 to ensure output matches.
Example 2: n=12, m=17, r=9, k=40. Let's compute manually? Hard, but we trust.
But we should test with code mental or small script? Since we can't run, but we can reason about algorithm correctness.
Now check for potential integer overflow: f and g up to min(r, n - r + 1) ≤ 1e5, product up to 1e10, sum up to 1e15, all fits in 64-bit signed.
Now edge case: If k = nm, we need all cells. Our algorithm would pop all nm products? That would be up to 1e10 pops, not feasible. But problem states k ≤ min(nm, 1e5). So k never exceeds 1e5, so we only need top k. So if k = nm and nm ≤ 1e5, that means nm <= 1e5, so n,m small. Then our heap method would still work; but if nm <= 1e5, we could also just compute all products and sort, which is simpler. But heap still works, but initial heap size n could be up to maybe 1e5, but total pops = nm (which is ≤ 1e5) so fine. So heap method works for all allowed k.
Now check for potential duplicate products due to identical values: The merging method handles duplicates fine.
Now I'd like to confirm with another scenario: n=1, m=100000, r=1, k=100000. n=1, f = [1]; g all 1's? Actually r=1, f(i)=1 for all i (only one row). g(j)=1 for all j. So all products=1. Our merging: f=[1], g sorted descending all 1. initial heap: (1,0,0). pop => sum 1, push (1,0,1) etc. It will pop k times, sum = k. T = (1-1+1)(100000-1+1)=1100000=100000. Expected = k / T = 1. Actually if k = 100000, all cells filled, expected = 1 (since each scoop catches exactly one fish if placed anywhere? Actually if r=1, scoop is 1x1. Random placement picks a cell uniformly among all cells? Wait total positions = n - r + 1 = 1, m - r + 1 = m, so T=1*m = m. The probability that a given fish in cell (1,j) is caught: number of scoop positions covering that cell: since scoop is 1x1, only if lower-left corner is exactly at (1,j) (since r=1). So probability = 1/T if the fish is in a cell that is reachable? Actually lower-left corner ranges a from 1 to n - r + 1 = 1, b from 1 to m - r + 1 = m. So the scoop positions correspond one-to-one with cells? Actually with r=1, the scoop covers exactly one cell: the cell at the lower-left corner. So the scoop placement selects a cell uniformly from the grid? Not exactly: the lower-left corner ranges over rows 1 to 1, columns 1 to m. So it selects column j uniformly from 1..m. So the scoop covers cell (1,j). So if we put fishes in all m cells, each scoop catches exactly one fish (the one at the selected column). Expected number = 1. So sum of probabilities: each fish has probability 1/m, sum over m fishes = 1. Our algorithm: sum_products = sum of f[i]*g[j] for selected cells: f[i]=1, g[j]=1 for all j, so sum_products = k (if k=m, sum_products = m). T = m, expected = m/m =1. So correct.
Now check n=2, m=2, r=2, k=4? But k ≤ n*m =4, and also ≤1e5. So possible. r=2, n=2,m=2 => n-r+1=1,m-r+1=1 => T=1. f(i): i=1: min(1,1)=1, max(1,0)=1 =>1; i=2: min(2,1)=1, max(1,1)=1 =>1. So f=[1,1]; g=[1,1]. All products=1. Sum_products=4, T=1 => expected=4. That makes sense: the scoop is the whole pond, always catches all fishes. So maximum expected is 4 if we place 4 fishes. Good.
Now, but is it always optimal to choose cells with highest probability? Since expected value is linear, yes. So the problem reduces to selecting k cells with largest f(i)*g(j). And the algorithm we described yields the sum of top k products.
Now we need to output with high precision. Use double and print with e.g., 10 decimal places.
Now let's test some more cases manually to ensure correctness.
Case: n=5, m=5, r=3, k=5. Compute f and g. Let's compute f:
n=5,r=3 => A = n - r + 1 = 3.
For i=1: min(1,3)=1, max(1, -1)=1 =>1
i=2: min(2,3)=2, max(1,0)=1 =>2-1+1=2
i=3: min(3,3)=3, max(1,1)=1 =>3-1+1=3
i=4: min(4,3)=3, max(1,2)=2 =>3-2+1=2
i=5: min(5,3)=3, max(1,3)=3 =>3-3+1=1
So f = [1,2,3,2,1]. Similarly g same.
Sorted f descending: [3,2,2,1,1]; sorted g descending: [3,2,2,1,1].
Now top k=5 products: we need largest 5 from the 5x5 matrix.
List all products (descending):
33=9
32=6 (two of them: row with 3 and g=2, there are two columns with 2, so two 6s)
23=6 (two rows with 2 and col with 3, but careful: 23 =6 as well. So total number of 6s: there are two rows with 2 and one col with 3 -> 2, plus one row with 3 and two cols with 2 -> 2, total 4? Actually f: one 3, two 2s, two 1s. g: one 3, two 2s, two 1s. So count of product 6:
- (f=3, g=2): 1*2 =2 entries (since two columns with 2)
- (f=2, g=3): 21 =2 entries (since two rows with 2 and one column with 3)
Total 4 entries of 6. But note that (f=3,g=3)=9 is one entry. Next product after 6 maybe 31=3 (two columns of 1) => 2 entries of 3? Actually 31=3, there are two 1s in g => 2 entries. Also 22=4? Wait 2*2=4. Let's compute all product values:
- 3*3=9 (1)
- 3*2=6 (2)
- 2*3=6 (2)
- 2*2=4 (4? Actually two rows with 2 and two columns with 2 => 4 entries)
- 3*1=3 (2)
- 1*3=3 (2)
- 2*1=2 (4? two rows with 2 and two columns with 1 =>4)
- 1*2=2 (4? two rows with 1 and two columns with 2 =>4)
- 1*1=1 (4? two rows with 1 and two columns with 1 =>4)
But these counts exceed 25 but that's okay; these are counts.
Now top 5 sorted descending values: first is 9, then 6,6,6,6? That would be 5 items: 9 and four 6's = 5 items. So sum = 9 + 64 = 9+24=33. So expected = 33 / T. T = (5-3+1)(5-3+1) = 3*3=9. Expected = 33/9 = 11/3 ≈ 3.6666666667. But is that achievable? Since we can only place k=5 fishes. With f and g as above, can we achieve sum of products = 33? The top five cells by product are: (row with f=3, col with g=3) product 9; then cells (3,2a) product 6; (3,2b) product 6; (2a,3) product 6; (2b,3) product 6. So yes, choose those five cells. Sum = 9+6+6+6+6=33. So expected = 33/9 = 3.666... Our merging algorithm should produce that.
Now confirm merging: f (original order) = [1,2,3,2,1] but we need not sort f; we'll sort g descending. But if we don't sort f, the rows are not necessarily in order of decreasing f. But that's okay because the heap will contain each row's head (product with largest g). However, if we don't sort f, the initial heap will contain for each row i: f[i] * g_sorted[0] (g_sorted[0] = 3). So initial products: row0:13=3; row1:23=6; row2:33=9; row3:23=6; row4:13=3. So heap entries: (9,2,0), (6,1,0), (6,3,0), (3,0,0), (3,4,0). Pop (9,2,0): sum=9, push row2 j=1: 32=6 (since g_sorted[1]=2). Next pop max: there are three 6s: (6,1,0), (6,3,0), (6,2,1). Pop one, say (6,1,0): sum=15, push row1 j=1: 2*2=4. Continue. But we need five pops; after popping 9 and four 6s, sum=33. So it works.
Thus algorithm is correct.
Now we need to consider a corner: if we sort g descending, we have g_sorted[0] as max. But we must also consider that the maximum product might come from a row with a smaller f but a larger g? Actually g_sorted is sorted, so g_sorted[0] is the overall max g. So the maximum product is max_i f[i] * g_sorted[0]. That's correct because max over all pairs is max_i f[i] * max_j g[j]. So initial heap entries are all f[i] * g_max, which includes the global max. Good.
Now what about columns? Since we treat rows as lists, each column appears only once per row. That's fine.
Now is there any scenario where the merging algorithm fails because rows have different lengths? They all have same length m. So fine.
Now one more nuance: The product values are f[i]*g_sorted[j]. However, g_sorted[j] is the j-th largest g value, but note that if there are duplicate g values, the order among them is arbitrary. But that doesn't affect the set of products; each product appears exactly once regardless of order. Since the lists are sorted descending, duplicates are consecutive; but when we have duplicates, the order among them doesn't matter for merging as they are equal.
Thus the merging algorithm is correct and simpler.
Now we must also consider that k might be larger than n * number_of_unique_products? But k ≤ n*m, so fine.
Now implement steps:
-
Read integers n, m, r, k.
-
Compute A = n - r + 1, B = m - r + 1. T = (long long)A * B.
-
Compute f array (size n) as described.
For i from 0 to n-1 (or 1-index):
x = i+1
left = max(1, x - r + 1)
right = min(x, A)
f[i] = right - left + 1
Similarly g array (size m):
y = j+1
left = max(1, y - r + 1)
right = min(y, B)
g[j] = right - left + 1
-
Sort g in descending order. (We can use sort and then reverse, or sort with greater comparator).
Not necessary to sort f.
-
Use a priority queue (max-heap) where each element is a tuple (product, row_index, col_index). In C++, we can use priority_queue<pair<long long, pair<int, int>>>. This will sort by product first (largest). For tie-breaking, any is fine.
-
Initialize: for each i from 0 to n-1:
long long prod = f[i] * g[0]; // g[0] is max
heap.push({prod, {i, 0}});
But careful: If m == 0? m>=1, so fine.
-
long long sum_prod = 0;
for (int t = 0; t < k; ++t) {
auto top = heap.top(); heap.pop();
long long prod = top.first;
int i = top.second.first;
int j = top.second.second;
sum_prod += prod;
if (j + 1 < m) {
heap.push({f[i] * g[j+1], {i, j+1}});
}
}
-
double expected = (double) sum_prod / T;
cout << fixed << setprecision(10) << expected << endl;
Now we need to verify that this works when m is 1. Then g sorted descending has one element, j+1 < m is false, so after popping initial n entries, we will only pop from heap. Since we need k ≤ n*m = n, we will pop at most n entries. That's fine. Similarly, if n=1, initial heap has one entry, then we keep pushing next columns until we pop k.
Now test with n=1,m=5,r=1,k=5: f=[1], g computed: m=5,r=1 => B=5. For j=1: min(1,5)=1, max(1,1)=1 =>1. So g=[1,1,1,1,1]. Sorted g: [1,1,1,1,1]. Initial heap: (1*1=1,0,0). pop -> sum=1, push (1,0,1). pop -> sum=2, push (1,0,2). etc. Sum 5, T=5, expected=1. Good.
Now test with n=1,m=5,r=3,k=5? But r must be ≤ min(n,m)=1, so r=3 not allowed. So fine.
Now consider n=100000,m=100000,r=50000,k=100000. f and g arrays size 100k each. Sorting g O(m log m). Initial heap pushes 100k entries, each product computed as f[i]g_max. f[i] up to min(r, n-r+1) = min(50000, 50001) = 50000? Actually n=100000, r=50000 => n-r+1=50001. So max f = min(r, n-r+1) = 50000. So f values up to 50000. g_max up to 50000. product up to 2.5e9, sum up to maybe 1e15, fine. Heap operations O((n+k) log n) ~ 200klog(100k) ~ 200k*17=3.4M, fine.
Now we must confirm that we indeed pick the cells with maximum products. The merging algorithm picks the maximum across row heads. Since each row's list is sorted descending, the global max after each pop is among the heads. This is exactly the algorithm for merging sorted lists. So yes.
Now consider if we had sorted f descending as well, we could perhaps reduce initial heap size by only considering rows that can possibly be in top k. But not necessary.
Now note: In the merging approach, the heap size might become up to n at the beginning, then potentially shrink as rows exhaust? Actually as we pop rows, we push next column from that row, so heap size remains n (if m>1) because we always have one element per row until a row exhausts. Once a row exhausts (j reaches m-1 and we pop its last element, then we don't push further, so heap size decreases by 1. But overall heap size never exceeds n. So memory fine.
Now verify that the product f[i]*g[j] is integer; we use long long.
Now check for integer overflow when computing f[i]*g[j] if f and g are int (32-bit) up to 1e5, product up to 1e10 which fits in 64-bit. But if we store f and g as int, then f[i]*g[j] may be computed as int multiplication then converted to long long, which could overflow if product > 2^31-1. So we should cast to long long before multiplication: either store f and g as long long, or cast when computing product: (long long)f[i]*g[j]. I'll store f and g as vector to avoid issues.
Now ensure we use correct data types: T = (long long)(n - r + 1)*(m - r + 1) may overflow if we multiply two ints up to 1e5 each -> up to 1e10, fits in 64-bit but to be safe use long long.
Now check for edge case: n - r + 1 might be large up to 1e5, product up to 1e10, long long ok.
Now confirm with given examples.
Example 1: we did, output 2.0000000000.
Example 2: n=12, m=17, r=9, k=40. Let's attempt to compute manually to verify algorithm yields 32.8333333333.
Compute n=12, m=17, r=9.
A = n - r + 1 = 12 - 9 + 1 = 4.
B = m - r + 1 = 17 - 9 + 1 = 9.
So T = 4 * 9 = 36.
Now f(i) for rows: n=12, r=9, A=4.
Compute f(i) = min(i, A) - max(1, i - r + 1) + 1.
i from 1..12.
Let's compute f(i):
i=1: min(1,4)=1, max(1,1-9+1=-7)=1 =>1-1+1=1.
i=2: min(2,4)=2, max(1,2-9+1=-6)=1 =>2-1+1=2.
i=3: min(3,4)=3, max(1,3-9+1=-5)=1 =>3-1+1=3.
i=4: min(4,4)=4, max(1,4-9+1=-4)=1 =>4-1+1=4.
i=5: min(5,4)=4, max(1,5-9+1=-3)=1 =>4-1+1=4.
i=6: min(6,4)=4, max(1,6-9+1=-2)=1 =>4-1+1=4.
i=7: min(7,4)=4, max(1,7-9+1=-1)=1 =>4-1+1=4.
i=8: min(8,4)=4, max(1,8-9+1=0) => max(1,0)=1 =>4-1+1=4.
i=9: min(9,4)=4, max(1,9-9+1=1)=1 =>4-1+1=4.
i=10: min(10,4)=4, max(1,10-9+1=2)=2 =>4-2+1=3.
i=11: min(11,4)=4, max(1,11-9+1=3)=3 =>4-3+1=2.
i=12: min(12,4)=4, max(1,12-9+1=4)=4 =>4-4+1=1.
So f = [1,2,3,4,4,4,4,4,4,3,2,1] (size 12). Similarly for columns: m=17, r=9, B=9.
Compute g(j) for j=1..17:
j=1: min(1,9)=1, max(1,1-9+1=-7)=1 =>1-1+1=1.
j=2: min(2,9)=2, max(1,2-9+1=-6)=1 =>2-1+1=2.
j=3: min(3,9)=3, max(1,3-9+1=-5)=1 =>3-1+1=3.
j=4: min(4,9)=4, max(1,4-9+1=-4)=1 =>4-1+1=4.
j=5: min(5,9)=5, max(1,5-9+1=-3)=1 =>5-1+1=5.
j=6: min(6,9)=6, max(1,6-9+1=-2)=1 =>6-1+1=6.
j=7: min(7,9)=7, max(1,7-9+1=-1)=1 =>7-1+1=7.
j=8: min(8,9)=8, max(1,8-9+1=0)=1 =>8-1+1=8.
j=9: min(9,9)=9, max(1,9-9+1=1)=1 =>9-1+1=9.
j=10: min(10,9)=9, max(1,10-9+1=2)=2 =>9-2+1=8.
j=11: min(11,9)=9, max(1,11-9+1=3)=3 =>9-3+1=7.
j=12: min(12,9)=9, max(1,12-9+1=4)=4 =>9-4+1=6.
j=13: min(13,9)=9, max(1,13-9+1=5)=5 =>9-5+1=5.
j=14: min(14,9)=9, max(1,14-9+1=6)=6 =>9-6+1=4.
j=15: min(15,9)=9, max(1,15-9+1=7)=7 =>9-7+1=3.
j=16: min(16,9)=9, max(1,16-9+1=8)=8 =>9-8+1=2.
j=17: min(17,9)=9, max(1,17-9+1=9)=9 =>9-9+1=1.
So g = [1,2,3,4,5,6,7,8,9,8,7,6,5,4,3,2,1] (size 17). Now the maximum product is max f * max g = 4 * 9 = 36? Wait max f is 4? Actually from f, max is 4? But we have f values: we see 4 is max, also maybe 4 appears many times. f max = 4? Let's double-check f: i=4 yields 4, i=5..9 yield 4, so max=4. g max = 9. So product max = 36. However, note that there are f values of 4 and g values of 9, so product 36. But also note that f(i) could be up to min(r, A) = min(9,4)=4, indeed. So product max is 36.
Now we need top 40 products. Since total cells = 12*17=204, we can compute all products and sort to verify sum of top 40 and expected output 32.8333333333, which is sum_products / 36. So sum_products should be 32.8333333333 * 36 = 1182.0? 32.8333333333 * 36 = 32.8333333333 * 36 = (32 + 5/6?) Actually 32.8333333333 = 32 + 5/6? 5/6 ≈0.8333333, so 32 + 5/6 = (197/6?) Actually 32 = 192/6, plus 5/6 = 197/6 ≈ 32.83333333. Times 36 = (197/6)36 = 1976 = 1182. So sum_products = 1182. So we need to check if sum of top 40 products equals 1182.
Let's compute all products? Might be doable manually with some grouping. Let's list f array:
Indices (row 1..12):
1:1
2:2
3:3
4:4
5:4
6:4
7:4
8:4
9:4
10:3
11:2
12:1
g array (col 1..17):
1:1
2:2
3:3
4:4
5:5
6:6
7:7
8:8
9:9
10:8
11:7
12:6
13:5
14:4
15:3
16:2
17:1
Now products. To find top 40, we can think in terms of distribution.
Let's sort f descending: f sorted: 4,4,4,4,4,4,4? Actually count of 4s: rows 4,5,6,7,8,9 -> that's 6 rows with f=4. Wait check rows: 4,5,6,7,8,9 -> that's 6 rows (i=4,5,6,7,8,9) all have f=4? From earlier: i=4:4; i=5:4; i=6:4; i=7:4; i=8:4; i=9:4. Yes 6 rows. Then f=3: rows 3 and 10 -> 2 rows. f=2: rows 2 and 11 -> 2 rows. f=1: rows 1 and 12 -> 2 rows. So total 12 rows. So f multiset: 4(x6), 3(x2), 2(x2), 1(x2).
g sorted descending: Let's sort g descending: 9,8,8,7,7,6,6,5,5,4,4,3,3,2,2,1,1? Actually from computed: g values: 1,2,3,4,5,6,7,8,9,8,7,6,5,4,3,2,1. So sorted descending: 9, 8,8, 7,7, 6,6, 5,5, 4,4, 3,3, 2,2, 1,1. Let's count: 9:1; 8:2; 7:2; 6:2; 5:2; 4:2; 3:2; 2:2; 1:2. So total 17: 1+2+2+2+2+2+2+2+2 = 1+16=17 correct.
Now product set: we need top 40. Since total cells = 204, top 40 is about top 20%.
We can compute the product frequencies:
Define rows by f value groups: f=4 (6 rows), f=3 (2 rows), f=2 (2 rows), f=1 (2 rows).
Define columns by g value groups: g=9 (1 col), 8 (2 cols), 7 (2), 6 (2), 5 (2), 4 (2), 3 (2), 2 (2), 1 (2).
Now product for a row with f=a and column with g=b is a*b.
We need sum of the 40 largest a*b.
We can think of generating products in descending order.
Highest product is 4*9=36. Count: rows with f=4 (6) * cols with g=9 (1) = 6 cells with product 36.
Next product: 48=32 (since 39=27 but 48=32 > 27). So 48 is next. Count: f=4 rows (6) * g=8 cols (2) = 12 cells with product 32.
But also 39=27, and 29=18, 1*9=9. So after 36, 32 is next.
After 48=32, next is 39=27? Actually compare 47=28, 39=27, so 47=28 > 27. So next is 47=28. Count: f=4 (6) * g=7 (2) = 12 cells with 28.
Then 3*9=27. Count: f=3 (2) * g=9 (1) = 2 cells with 27.
Then 4*6=24. Count: f=4 (6) * g=6 (2) = 12 cells.
Then 38=24? Wait 38=24 as well. So product 24 can come from (f=4,g=6) and (f=3,g=8). Also 212? no 212 not. Also 2*? Let's compare 45=20, 37=21, 29=18, 1? So after 24, maybe 38=24 is same value, and 46=24. So all these 24s. Next after 24, we have 37=21, 45=20, 2*9=18, etc.
We need to accumulate counts until we have at least 40 cells.
Let's list products in descending order with counts.
We'll generate pairs (a,b) sorted by product descending. Since both f and g have multiple values, we can think of merging.
One systematic way: Since f values are limited (4,3,2,1) and g values limited (9,8,7,6,5,4,3,2,1), we can list all possible products a*b and sort. But careful: The order among equal products doesn't matter. So compute each product value and count.
Product values:
For a=4:
b=9: 36, count = 61 = 6
b=8: 32, count = 62 = 12
b=7: 28, count = 62 = 12
b=6: 24, count = 62 = 12
b=5: 20, count = 62 = 12
b=4: 16, count = 62 = 12
b=3: 12, count = 62 = 12
b=2: 8, count = 62 = 12
b=1: 4, count = 6*2 = 12
For a=3:
b=9: 27, count = 21 = 2
b=8: 24, count = 22 = 4
b=7: 21, count = 22 = 4
b=6: 18, count = 22 = 4
b=5: 15, count = 22 = 4
b=4: 12, count = 22 = 4
b=3: 9, count = 22 = 4
b=2: 6, count = 22 = 4
b=1: 3, count = 2*2 = 4
For a=2:
b=9: 18, count = 21 = 2
b=8: 16, count = 22 = 4
b=7: 14, count = 22 = 4
b=6: 12, count = 22 = 4
b=5: 10, count = 22 = 4
b=4: 8, count = 22 = 4
b=3: 6, count = 22 = 4
b=2: 4, count = 22 = 4
b=1: 2, count = 2*2 = 4
For a=1:
b=9: 9, count = 21 = 2
b=8: 8, count = 22 = 4
b=7: 7, count = 22 = 4
b=6: 6, count = 22 = 4
b=5: 5, count = 22 = 4
b=4: 4, count = 22 = 4
b=3: 3, count = 22 = 4
b=2: 2, count = 22 = 4
b=1: 1, count = 2*2 = 4
But careful: Some product values appear from multiple (a,b) combinations, e.g., product 24 appears from (4,6) and (3,8). Count of 24: from a=4,b=6: 12; from a=3,b=8: 4; total 16. Similarly product 12 appears from (4,3):12, (3,4):4, (2,6):4, (1,12?) Actually (1,12) not; (1,12) not exist. So total count for 12: from a=4,b=3:12, a=3,b=4:4, a=2,b=6:4, and also a=1,b=12? no. So total 12+4+4 = 20. Also maybe from a=?? a=6? no. So we need to merge counts for same product.
But for our top 40, we can just take the highest product values until we accumulate 40 cells.
Let's list product values in descending order with cumulative counts.
First product 36 (count=6). Cumulative 6.
Next 32 (count=12). Cumulative 18.
Next 28 (count=12). Cumulative 30.
Next 27 (count=2). Cumulative 32.
Now we still need 8 more cells (since k=40). Next product after 27? Next highest product among remaining: What is next? After 27, we have 24 (from 46 and 38) but also 28? already taken. Also 45=20? But 46=24, 38=24, also maybe 4? Wait also 4*? Check: 46=24, 38=24, 212? no, 2? Not. Also 4*? Actually after 27, next candidate could be 46=24 and 38=24 and also 4*? Let's compute all possible product values not yet taken: The next highest product is 24? But we also have 4*? Actually we have 46=24, 38=24, and also maybe 4*? The next after 28 and 27, we should consider 26? Not present. 25? Not. So 24 is next. But also 4*? Wait what about 4*? The next product after 28 is 27, after 27 is 24. But check 4*? 4*? 4*? Actually 4*? The sequence: 49=36, 48=32, 47=28, 39=27, then 46=24, 38=24, 2*? 2*? 212 not, 2? 2*? 2*? So yes 24 is next. Also maybe 4*? Actually 4*? Could there be 4*? After 46=24, next is 37=21? But 45=20, 37=21, so 21 > 20, so 21 would be after 24? Wait we need to sort correctly: after 27, we have 24. Then after 24, next is 21? Actually also there might be 4*? 4*? Let's list all distinct product values in descending order:
- 36
- 32
- 28
- 27
- 24 (from 46 and 38)
- 21 (from 3*7)
- 20 (from 4*5)
- 18 (from 36 and 29)
- 16 (from 44 and 28? Actually 44=16, 28=16, also 1*16 no)
- 15 (from 3*5)
- 14 (from 2*7)
- 12 (multiple)
- etc.
But we must ensure we haven't missed any product that lies between these: e.g., 4*? 4*? The next after 24 is 21? Actually 4*? 45=20, 4? 4*? 4*? There is no 4*? 4*? after 6, the next g for group 4 is 5, giving 20. 3*7=21. So indeed 21 > 20, so after 24 comes 21.
But also there is possibility of product 25? none. So list seems fine.
Now after cumulative 32 from 36,32,28,27, we need 8 more cells. Next product is 24. How many cells have product 24? Let's compute total count for product 24:
- from a=4,b=6: count = rows with f=4 (6) * columns with g=6 (2) = 12.
- from a=3,b=8: rows f=3 (2) * columns g=8 (2) = 4.
Total = 16.
But we need only 8 cells to reach 40. So we will take 8 of the 24-valued cells. Since all 24 are equal, any 8 will do. The sum contributed will be 8 * 24 = 192.
Now total sum of products from top 40 = sum from previous + 192.
Previous sum: sum of products from 36,32,28,27.
Compute sum from first 6 cells of 36: 636 = 216.
12 cells of 32: 1232 = 384.
12 cells of 28: 1228 = 336.
2 cells of 27: 227 = 54.
Total so far: 216+384=600, +336=936, +54=990.
Now add 8*24 = 192 gives total 1182. That matches the required sum 1182. So expected = 1182/36 = 32.8333333333... Good.
Thus our algorithm should produce sum=1182, and expected 1182/36=32.8333333333.
Now we must ensure that our merging algorithm would indeed pick 8 cells of product 24. It will, because after popping 32 cells (6+12+12+2=32) we have 8 more pops, and at that point the heap's top will be 24 (since all remaining heads have product 24). But note: there may also be product 24 from many rows. The merging algorithm will pop 24s until we have 40 total. So sum will be correct.
Thus algorithm works for example.
Now consider potential pitfalls: If k is large and we need to pop many items, but we only push one per pop, we may exhaust some rows before we get to k. That's fine.
Now think about alternative approach: maybe we can directly compute sum of top k products without heap using combinatorial counts of f and g frequencies. Since k ≤ 1e5, heap is fine. But we could also sort f and g descending and then use a two-pointer or binary search to count how many products >= threshold, and then compute sum of those products, and then handle partial threshold. That might be more efficient? But heap is simpler.
Given constraints, heap solution is acceptable.
Now confirm that we do not need to consider the fact that each cell is unique; the merging algorithm respects uniqueness because each pair (i,j) appears exactly once.
Now we need to code.
Potential issues: The heap with n=100000 initial pushes may be heavy but okay. In C++, priority_queue push/pop are O(log size). For n=100000, building heap by pushing each individually is O(n log n). Could be optimized by heapify but not needed.
Now need to define comparator or use default. Since we use pair<long long, pair<int,int>>, default compares first then second, etc. Since we want max-heap, and default is max based on first (largest first) because priority_queue uses std::less by default, which for pairs compares lexicographically; the largest first means the highest product. So default works as max-heap. So we can declare:
priority_queue<pair<long long, pair<int, int>>> pq;
But note: if we push negative to get min-heap; but we want max, so it's fine.
Now visited set not needed because we are using row-wise merging.
Now edge: if m=0? Not possible since m>=1.
Now memory: f (n), g (m). g sorted.
Now implement.
But there is nuance: In the merging algorithm, we treat each row as a list based on sorted g. But we need to ensure that for each row we push only one element initially and then progress along columns. However, if we have many rows and k is small, we push all rows initially, which might be wasteful but acceptable. However, consider n=100000, m=100000, k=1. We push 100000 entries into heap, then pop one, and done. That's 100000 log 100000 operations, which is about 1.7 million comparisons, still fine. But we could optimize by finding max product directly: max_f * max_g, where max_f is max over f, max_g is max over g. But our algorithm would still push all, but that's okay given constraints 1e5.
But if both n and m are 1e5, and k=1, the heap approach still does 1e5 pushes and 1 pop. That's maybe 1e5 * log(1e5) ~ 1.7e6 operations, which is fine in C++. So it's acceptable.
However, if we wanted to be slightly more efficient, we could compute max_f and max_g, and then only push rows that have f[i] == max_f? Not necessary.
Now also note that g sorted descending, but we also need to know the original g values? No.
Now test edge: n=100000, m=1, r=1, k=100000. Then f = [1,1,...] (n times). g = [1] (since m=1). Sorted g = [1]. initial heap: n entries each product =1. Then we pop k=100000 times, but there are only n=100000 entries, so we will pop all. Each pop will not push because j+1 < m fails. So we pop all n, sum = n, T = (n - 1 + 1)(1 - 1 + 1)= n1 = n. Expected = 1. So correct.
Now think about performance: using pair<long long, pair<int,int>> is fine.
Now final answer is sum_products / T as double. Output with precision 10.
Now let's write the solution.
But wait: The problem states that k fishes are placed in distinct cells. We assume we can choose any cells. The expected number is sum of probabilities. Yes.
Now we might need to consider if the scoop net is placed randomly among (n - r + 1)*(m - r + 1) positions. Yes.
Now check corner: r could be 0? No, r >=1.
Now confirm f(i) formula for i such that i - r + 1 might be > A? Actually the formula is fine.
Alternative simpler formula: f(i) = min(i, n - r + 1, r, n - i + 1?) Not needed.
Now think about integer division: We compute sum_prod as long long, then cast to double.
Now edge: If T is 0? But r ≤ n,m, so n - r + 1 >=1, similarly m - r + 1 >=1, so T >=1.
Now output format: Print a single number with absolute/relative error 1e-9. So 10 decimal digits should be enough.
Now I'll produce final solution.
But there is one more nuance: The merging algorithm uses g sorted descending. However, we must consider that the product f[i]*g_sorted[j] for different rows may be equal, but we don't need to differentiate.
Now confirm that we aren't missing any cell: Since we iterate over all rows i (0..n-1) and for each row we consider columns j from 0..m-1 in descending order, we cover all combinations exactly once. Yes.
Now potential bug: When we push initial entries, if m=0 (not possible), but if m is positive, we push. Good.
Now code:
Pseudo:
int main() {
int n, m, r, k;
cin >> n >> m >> r >> k;
long long A = n - r + 1;
long long B = m - r + 1;
long long T = A * B;
vector f(n), g(m);
for (int i = 1; i <= n; ++i) {
long long left = max(1LL, i - r + 1LL);
long long right = min((long long)i, A);
f[i-1] = right - left + 1;
}
for (int j = 1; j <= m; ++j) {
long long left = max(1LL, j - r + 1LL);
long long right = min((long long)j, B);
g[j-1] = right - left + 1;
}
sort(g.begin(), g.end(), greater());
// don't sort f
priority_queue<pair<long long, pair<int, int>>> pq;
for (int i = 0; i < n; ++i) {
pq.push({f[i] * g[0], {i, 0}});
}
long long sum_prod = 0;
for (int t = 0; t < k; ++t) {
auto top = pq.top(); pq.pop();
long long prod = top.first;
int i = top.second.first;
int j = top.second.second;
sum_prod += prod;
if (j + 1 < m) {
pq.push({f[i] * g[j+1], {i, j+1}});
}
}
double expected = (double)sum_prod / T;
cout << fixed << setprecision(10) << expected << endl;
return 0;
}
Now test with example 1: n=3,m=3,r=2,k=3.
Compute A=2,B=2,T=4.
f: i=1: left=max(1,0)=1, right=min(1,2)=1 =>1; i=2: left=max(1,1)=1, right=min(2,2)=2 =>2; i=3: left=max(1,2)=2, right=min(3,2)=2 =>1 => f=[1,2,1]
g: similarly [1,2,1], sorted descending => [2,1,1]
Initial heap:
i=0: 12=2
i=1: 22=4
i=2: 12=2
Heap: (4,(1,0)), (2,(0,0)), (2,(2,0)).
pop: prod=4, i=1,j=0, sum=4, push j+1=1: 21=2 -> (2,(1,1)).
heap now: (2,(0,0)), (2,(2,0)), (2,(1,1)).
pop: say (2,(0,0)): sum=6, push (0,1): 11=1 -> (1,(0,1)).
heap: (2,(2,0)), (2,(1,1)), (1,(0,1)).
pop: (2,(2,0)): sum=8, push (2,1):11=1.
Done 3 pops sum=8, expected=8/4=2. Good.
Example 2: we already reasoned.
Now consider if n is large and m is 1: g sorted descending has one element. Then initial heap pushes n entries. Then we pop k entries, but after each pop we don't push because j+1 < m false. So we will pop min(k, n) entries. Since k ≤ n*m = n, we pop all k <= n. Works.
Now consider if m is large and n is 1: Then f has one element. Initial heap: one entry (f[0]*g[0], 0,0). Then each pop pushes next column until we have popped k. So that works.
Now complexity is fine.
Now we should check if there is any case where the product f[i]*g[j] might be 0? Since r ≥1, f(i) and g(j) are at least 1. So all products positive.
Now potential overflow: f and g up to 1e5, product up to 1e10, sum up to 1e15. All within 64-bit.
Now precision: double can represent integers up to 2^53 ≈ 9e15 exactly, so sum_prod may be up to 1e15, still representable exactly as integer in double. T up to 1e10. The division might produce a non-terminating decimal but double has about 15-16 decimal digits of precision, so relative error within 1e-9 is fine.
Now we should confirm that the algorithm indeed yields the maximum expected value. Since expected value = sum of probabilities /? Actually sum of probabilities = sum of products / T. So maximizing expected value = maximizing sum of products. Since we choose cells with largest products, it's optimal.
Now finalize.
But wait: There is nuance: The expected number of caught fishes is the average over scoop positions of number of fishes inside. This equals sum over fishes of probability that the scoop covers the fish. That probability is as computed. So indeed we need to maximize sum of p_ij. So picking top k p_ij is optimal.
Now about the selection: Since the probabilities are independent, any set of k distinct cells with the highest p_ij is optimal. There's no other constraints.
Thus solved.
Now we should provide answer with explanation.
Now consider if we might use long double for more precision? Not needed.
Now we produce final solution.
But before finalizing, let's think about potential alternative: maybe we can compute the top k products by considering the distribution of f and g frequencies and using a binary search to find threshold and compute sum quickly, which might be faster for huge k (but k limited to 1e5). However, heap is simpler and within limits.
Now test with a random small case manually to ensure no off-by-one.
Suppose n=2,m=2,r=1,k=1.
A = 2, B=2, T=4.
f: i=1: left=max(1,1)=1, right=min(1,2)=1 =>1; i=2: left=max(1,2)=2? Actually i=2: left=max(1,2-1+1=2)=2, right=min(2,2)=2 =>1 => f=[1,1]
g similarly [1,1] sorted descending [1,1].
Initial heap: row0:11=1; row1:11=1. heap has two entries of 1. Pop one: sum=1, expected=1/4=0.25. But the maximum expected is 0.25? Since any fish has probability 1/4, so expected max is 0.25. Good.
Now test n=2,m=2,r=2,k=1.
A=1,B=1,T=1.
f: i=1: left=max(1,1-2+1=0)=1, right=min(1,1)=1 =>1; i=2: left=max(1,2-2+1=1)=1, right=min(2,1)=1 =>1 => f=[1,1]; g=[1,1]. Sorted g=[1,1]. Initial heap: two entries of 1. Pop one sum=1, expected=1/1=1. So max expected is 1 (placing one fish anywhere ensures it's always caught). Correct.
Now test n=4,m=5,r=3,k=2. Compute manually:
A=2, B=3.
f: i=1: left=max(1,1-3+1=-1)=1, right=min(1,2)=1 =>1
i=2: left=max(1,2-3+1=0)=1, right=min(2,2)=2 =>2-1+1=2
i=3: left=max(1,3-3+1=1)=1, right=min(3,2)=2 =>2-1+1=2
i=4: left=max(1,4-3+1=2)=2, right=min(4,2)=2 =>2-2+1=1 => f=[1,2,2,1]
g: j=1: left=max(1,1-3+1=-1)=1, right=min(1,3)=1 =>1
j=2: left=max(1,2-3+1=0)=1, right=min(2,3)=2 =>2-1+1=2
j=3: left=max(1,3-3+1=1)=1, right=min(3,3)=3 =>3-1+1=3
j=4: left=max(1,4-3+1=2)=2, right=min(4,3)=3 =>3-2+1=2
j=5: left=max(1,5-3+1=3)=3, right=min(5,3)=3 =>3-3+1=1 => g=[1,2,3,2,1]
Sorted g descending: [3,2,2,1,1].
Now products: For each row (f):
row0:13=3,12=2,12=2,11=1,11=1
row1:23=6,22=4,22=4,21=2,21=2
row2:23=6,22=4,22=4,21=2,21=2
row3:13=3,12=2,12=2,11=1,11=1
Top 2 products: 6 and 6 (two cells). Sum=12. T=AB=23=6. Expected=12/6=2. So maximum expected=2. Indeed, we can put fishes in the two cells with product 6 (these correspond to rows with f=2 and column with g=3). So algorithm should produce that. Let's simulate:
Initial heap: push for each row i:
i=0: 13=3
i=1: 23=6
i=2: 23=6
i=3: 13=3
Heap: (6,1,0),(6,2,0),(3,0,0),(3,3,0)
Pop (6,1,0): sum=6, push (2*2=4,1,1)
Heap now: (6,2,0),(4,1,1),(3,0,0),(3,3,0)
Pop (6,2,0): sum=12, push (4,2,1)
Now we have popped 2, sum=12, expected=2. Works.
Now confirm that if k=3, the third largest product is 4? Actually after two 6's, we have many 4's. So sum would be 12+4=16, expected=16/6≈2.6667. So algorithm would pick a 4 next.
All good.
Now we should consider if there is any scenario where the merging algorithm fails due to not sorting f. Actually, it's not necessary to sort f, because each row's head is f[i]*g_max. The heap will contain all these. But is it possible that a row with smaller f but larger g later (beyond index 0) could produce a product larger than some other row's current head? Since we always keep the head for each row, the maximum product among all unpopped cells is indeed the maximum among the heads. After popping a head from row i, we push the next element in that row, which is f[i]*g_next. That next element could still be larger than some other row's head? That's fine; the heap will handle.
Now, is there any risk that we might need to consider a row's later element before some other row's head if the row's head is not the maximum but later element might become the maximum after some pops? But that's handled by the heap because each row contributes its current best, and when we pop a row's head, we replace it with its next best. So it's exactly like merging sorted lists. So it's correct.
Now one more nuance: When two rows have same f value, their lists are identical. That's fine.
Now about performance: In the merging algorithm, we push initial n entries. If n is 100000 and m is 100000, that's 100k pushes, each O(log n). That's okay.
But we also need to sort g descending. Sorting g of size up to 100000 is okay.
Now check if there is any case where k > nm? But k ≤ min(nm, 1e5), so k ≤ n*m.
Now final step: Write code.
But wait: There is another nuance: The product f(i)*g(j) corresponds to number of scoop placements covering cell (i,j). However, the cell (i,j) is distinct. Our merging algorithm uses f[i] (original order) and sorted g. But the sorted g is a permutation of columns. So the product we compute for a given (i, j_index) corresponds to row i and the column that originally had the g value at position j_index in the sorted order. Since we are just summing products, it's okay. However, we must ensure that we are not double counting columns. Because if we sort g, we lose the original column identity; but each column appears exactly once in the sorted list. So each (i, j_sorted) corresponds to a unique cell (i, original column of that g value). Since we never use the same column twice for the same row? Actually for a fixed row i, we consider all j_sorted from 0 to m-1. That covers each column exactly once, because each column appears exactly once in the sorted list. So it's a bijection between j_sorted and original columns. So we cover all cells exactly once. So fine.
Now about the visited set: Not needed because we treat each row's column progression linearly.
Now I'll write final answer.
But before final answer, let's consider if there's any alternative interpretation: Could there be a scenario where placing fishes in certain cells influences expected value non-linearly? No, because expectation is linear.
Now I think solution is solid.
Now I'll produce the final message with explanation and code.
But the problem asks: "Print a single number — the maximum possible expected number of caught fishes." So we output a floating point.
Now one more verification: In first example, output is 2.0000000000. Our algorithm yields 2.0.
Now second example yields 32.8333333333. We verified sum=1182, T=36, division = 1182/36 = 197/6 = 32.8333333333... Good.
Now ensure to use long long for A and B.
Now think about potential integer overflow when computing left/right: i - r + 1 could be negative, but we use max with 1, so fine.
Now edge: n and m up to 1e5, but r may be up to 1e5 as well. So i - r + 1 could be negative large, but we compare with 1, so okay.
Now code:
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
int n, m, r, k;
cin >> n >> m >> r >> k;
long long A = n - r + 1;
long long B = m - r + 1;
long long total_positions = A * B;
vector<long long> f(n);
for (int i = 1; i <= n; ++i) {
long long left = max(1LL, i - r + 1LL);
long long right = min((long long)i, A);
f[i-1] = right - left + 1;
}
vector<long long> g(m);
for (int j = 1; j <= m; ++j) {
long long left = max(1LL, j - r + 1LL);
long long right = min((long long)j, B);
g[j-1] = right - left + 1;
}
sort(g.begin(), g.end(), greater<long long>());
// max-heap: pair<product, pair<row_idx, col_idx_in_sorted_g>>
priority_queue<pair<long long, pair<int, int>>> pq;
for (int i = 0; i < n; ++i) {
pq.push({f[i] * g[0], {i, 0}});
}
long long sum_products = 0;
for (int t = 0; t < k; ++t) {
auto top = pq.top(); pq.pop();
long long prod = top.first;
int i = top.second.first;
int j = top.second.second;
sum_products += prod;
if (j + 1 < m) {
pq.push({f[i] * g[j+1], {i, j+1}});
}
}
double expected = (double)sum_products / total_positions;
cout << fixed << setprecision(10) << expected << endl;
return 0;
}
Now this should be correct.
But we need to consider that the product f[i] * g[0] might be computed as long long * long long; we have f and g as long long, so product is long long. Good.
Now also note that total_positions could be up to 1e10, which fits in long long. So division yields double.
Now the heap may be large initially (n). That's fine.
Now we can also add a small optimization: If k is equal to nm (only possible if nm ≤ 1e5), we could just compute all products and sum them, but not needed.
Now check for potential time: For worst case n=100000,m=100000,k=100000, we will do initial n pushes (100k). Then for each of k pops, we push one more (if j+1 < m). Since m=100k, for rows that we pop, we may push up to k times, but note that each row can be popped multiple times? Actually each row will be popped as many times as the number of columns we take from that row. Since we only pop k times total, and we push at most one per pop, the total pushes = n (initial) + number_of_pushes_during_loop ≤ n + k. So total heap operations ≤ n + 2k? Actually each pop is an operation, each push is an operation. So total operations = n (initial pushes) + k (pops) + at most k (pushes from pops) = n + 2k ≤ 300k. So 300k heap ops, each O(log n) ~ 17, total ~ 5.1 million, fine.
But note: In each push during loop, we compute product f[i]*g[j+1]. That's O(1). Good.
Now we might want to store f as vector to save memory, but product as long long. It's fine.
Now ensure that g sorted descending; we used greater comparator.
Now confirm that we didn't forget to use long long for A and B in formulas.
Now finalize.
But I recall that there is a known Codeforces problem (maybe "New Year and the Acquaintance Estimation" or something else) but similar. This approach is standard.
Now I'll produce final answer with explanation. The expected number of caught fishes equals the sum over fishes of the probability that the scoop covers the fish.
For a cell at row (i) and column (j), that probability is
[
p(i,j) = \frac{f(i) \cdot g(j)}{(n-r+1)(m-r+1)},
]
where
[
f(i) = \min(i, n-r+1) - \max(1, i-r+1) + 1,
\qquad
g(j) = \min(j, m-r+1) - \max(1, j-r+1) + 1.
]
Thus we need to choose (k) distinct cells maximizing the sum of (f(i)g(j)), i.e., the sum of the (k) largest products from the Cartesian product of the multiset ({f(i)}) and ({g(j)}).
Because (f(i)) and (g(j)) are positive integers and (k \le 10^5), we can efficiently extract the (k) largest products using a max‑heap:
- Compute all (f(i)) (size (n)) and all (g(j)) (size (m)).
- Sort (g) in descending order.
- For each row (i), push ((f(i) \cdot g[0], i, 0)) into the heap.
- Repeatedly pop the largest element ((prod, i, j)), add it to the total, and if (j+1 < m), push ((f(i) \cdot g[j+1], i, j+1)).
This process merges the (n) sorted lists (each row gives a decreasing sequence (f(i) \cdot g[0], f(i) \cdot g[1], \dots)) and yields exactly the (k) largest products.
Finally, the answer is
[
\frac{\text{sum of the }k\text{ largest products}}{(n-r+1)(m-r+1)}.
]
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n, m, r, k;
cin >> n >> m >> r >> k;
long long A = n - r + 1;
long long B = m - r + 1;
long long total = A * B;
vector<long long> f(n), g(m);
for (int i = 1; i <= n; ++i) {
long long left = max(1LL, i - r + 1LL);
long long right = min((long long)i, A);
f[i-1] = right - left + 1;
}
for (int j = 1; j <= m; ++j) {
long long left = max(1LL, j - r + 1LL);
long long right = min((long long)j, B);
g[j-1] = right - left + 1;
}
sort(g.begin(), g.end(), greater<long long>());
// max-heap: (product, (row_index, column_index_in_sorted_g))
priority_queue<pair<long long, pair<int, int>>> pq;
for (int i = 0; i < n; ++i)
pq.push({f[i] * g[0], {i, 0}});
long long sum_prod = 0;
for (int t = 0; t < k; ++t) {
auto top = pq.top(); pq.pop();
long long prod = top.first;
int i = top.second.first;
int j = top.second.second;
sum_prod += prod;
if (j + 1 < m)
pq.push({f[i] * g[j+1], {i, j+1}});
}
double ans = (double)sum_prod / total;
cout << fixed << setprecision(10) << ans << '\n';
return 0;
}