To my boyfriend
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 667 Accepted Submission(s): 305
Problem Description
Dear Liao
I never forget the moment I met with you. You carefully asked me: "I have a very difficult problem. Can you teach me?". I replied with a smile, "of course". You replied:"Given a matrix, I randomly choose a sub-matrix, what is the expectation of the number of **different numbers** it contains?"
Sincerely yours,
Guo
Input
The first line of input contains an integer T(T≤8) indicating the number of test cases.
Each case contains two integers, n and m (1≤n, m≤100), the number of rows and the number of columns in the grid, respectively.
The next n lines each contain m integers. In particular, the j-th integer in the i-th of these rows contains g_i,j (0≤ g_i,j < n*m).
Output
Each case outputs a number that holds 9 decimal places.
Sample Input
1 2 3 1 2 1 2 1 2
Sample Output
Hint
Source
2017 Multi-University Training Contest - Team 2
又是一道统计的题目……
题目虽说是统计期望,但其实就是用所有矩形的权值和除以总的矩形个数。至于总的矩形个数,很容易求,对于一个点(i,j),以它为右下角的矩形个数就是i*j,由此总的矩形个数就是sigma(sigma(i*j))1<=i<=n,1<=j<=m。
那么我们现在考虑如何求所有矩形的权值和。和之前统计树上路径颜色数那题类似,本题还是分颜色来考虑。对于同种颜色在同一个矩形中出现的情况,我们规定这个贡献只计算到左上放的那个点上。由此,我们要对同种颜色的点按照坐标来排序。那么具体如何统计呢?我们以下面那个图为例(图我是用别人的,希望作者不要追究……):灰色
的点代表已经计算过的,黑色的点代表正在计算的,然后白色的点代表没有计算的。假设黑色点的坐标为(i,j),那么显然,现在的只包含现在这个点及优先级比他低的点的矩形的下界是i~n,总共n-i+1个。然后我们再枚举上界,上界是从i开始往上,知道第一个与它同列的已经更新过的点的下一行,这个必须得枚举。接着左右边界则要根据上界来确定了,当枚举第i行是,左边界l=1,右边界r=m;当枚举到i-1行时,l=1,r=9;当枚举到i-2时,l=2,r=5……一直往上维护这个左右界。如此下来,对于每一个枚举到的上界,对应的矩形个数就是(n-i+1)*(j-l+1)*(r-j+1)。
可以看到,每次的左右界l、r一定是一个不断缩小的范围,随着上界的移动每次不断的更新。这样子就可以不重复的把所有矩形给计算进来。总共有N*M种颜色,每种颜色要枚举上界,另外要维护l、r左右界,可以证明,均摊下来时间复杂度为O(N^2M^2/2),实际由于l、不断缩小,所以速度可观。具体见代码: