Expected Cells (Stretch)
This is a stretch problem.
There is an n×m grid of cells. Cell (r,c) has a positive weight wr,c. Let W=∑r,cwr,c.
Two cells A and B are sampled independently, with replacement. The probability of choosing cell (r,c) on a single sample is wr,c/W.
Let R be the smallest axis-aligned rectangle of grid cells that contains both sampled cells, and let A be the number of cells inside R (the area of R counted in cells). If A and B are the same cell, then R is that single cell and the area is 1.
Output the expected value of A.
It can be shown that the answer can be expressed as a rational number P/Q in lowest terms with Q coprime to 109+7. Output P⋅Q−1mod(109+7).
Input
The first line contains two integers n and m.
Each of the next n lines contains m integers. The c-th number on the r-th of these lines is wr,c.
Rows and columns are indexed from 1.
Output
Print a single integer: the expected number of cells in the bounding rectangle, modulo 109+7.
Constraints
- 1≤n,m
- n⋅m≤2⋅105
- 1≤wr,c≤106
Example 1
2 2
1 1
1 1
250000004
Explanation
All 16 ordered pairs of cells are equally likely. The expected area is 9/4, and 9⋅4−1≡250000004(mod109+7).
Example 2
1 1
5
1
Explanation
Both samples are the only cell, so the rectangle always has area 1.
Example 3
1 3
1 1 1
888888897
Explanation
The expected area is 17/9, and 17⋅9−1≡888888897(mod109+7).
Comments0
No comments yet
Be the first to comment.
New comment
Log in to join the discussion.