题目大意: 有一个 n × n n\times n n×n 的网格图,每次随机涂一格,一开始有 m m m 格已经涂了,问使得每行每列都至少有一个格子被涂需要的期望步数。
题解
设
f
[
i
]
[
j
]
f[i][j]
f[i][j] 表示还有
i
i
i 行
j
j
j 列没涂,那么有:
f
[
i
]
[
j
]
=
1
+
i
(
n
−
j
)
n
2
f
[
i
−
1
]
[
j
]
+
(
n
−
i
)
j
n
2
f
[
i
]
[
j
−
1
]
+
i
j
n
2
f
[
i
−
1
]
[
j
−
1
]
+
(
n
−
i
)
(
n
−
j
)
n
2
f
[
i
]
[
j
]
f[i][j]=1+\frac {i(n-j)} {n^2}f[i-1][j]+\frac {(n-i)j} {n^2}f[i][j-1]+\frac {ij} {n^2}f[i-1][j-1]+\frac {(n-i)(n-j)} {n^2}f[i][j]
f[i][j]=1+n2i(n−j)f[i−1][j]+n2(n−i)jf[i][j−1]+n2ijf[i−1][j−1]+n2(n−i)(n−j)f[i][j]
移项得到:
n
2
−
(
n
−
i
)
(
n
−
j
)
n
2
f
[
i
]
[
j
]
=
1
+
i
(
n
−
j
)
n
2
f
[
i
−
1
]
[
j
]
+
(
n
−
i
)
j
n
2
f
[
i
]
[
j
−
1
]
+
i
j
n
2
f
[
i
−
1
]
[
j
−
1
]
(
n
2
−
(
n
−
i
)
(
n
−
j
)
)
f
[
i
]
[
j
]
=
n
2
+
i
(
n
−
j
)
f
[
i
−
1
]
[
j
]
+
(
n
−
i
)
j
f
[
i
]
f
[
j
−
1
]
+
i
j
f
[
i
−
1
]
[
j
−
1
]
f
[
i
]
[
j
]
=
n
2
+
i
(
n
−
j
)
f
[
i
−
1
]
[
j
]
+
(
n
−
i
)
j
f
[
i
]
f
[
j
−
1
]
+
i
j
f
[
i
−
1
]
[
j
−
1
]
n
2
−
(
n
−
i
)
(
n
−
j
)
\begin{aligned} \frac {n^2-(n-i)(n-j)} {n^2}f[i][j]&=1+\frac {i(n-j)} {n^2}f[i-1][j]+\frac {(n-i)j} {n^2}f[i][j-1]+\frac {ij} {n^2}f[i-1][j-1]\\ (n^2-(n-i)(n-j))f[i][j]&=n^2+i(n-j)f[i-1][j]+(n-i)jf[i]f[j-1]+ijf[i-1][j-1]\\ f[i][j]&=\frac {n^2+i(n-j)f[i-1][j]+(n-i)jf[i]f[j-1]+ijf[i-1][j-1]} {n^2-(n-i)(n-j)} \end{aligned}
n2n2−(n−i)(n−j)f[i][j](n2−(n−i)(n−j))f[i][j]f[i][j]=1+n2i(n−j)f[i−1][j]+n2(n−i)jf[i][j−1]+n2ijf[i−1][j−1]=n2+i(n−j)f[i−1][j]+(n−i)jf[i]f[j−1]+ijf[i−1][j−1]=n2−(n−i)(n−j)n2+i(n−j)f[i−1][j]+(n−i)jf[i]f[j−1]+ijf[i−1][j−1]
递推即可,代码如下:
#include <cstdio>
#define maxn 2010
int n,m,h,l;
bool line[maxn],col[maxn];
double f[maxn][maxn];
double dp(int x,int y)
{
if(x==0&&y==0)return 0.0;
if(f[x][y])return f[x][y];
if(x)f[x][y]+=1.0*x*(n-y)*dp(x-1,y);
if(y)f[x][y]+=1.0*(n-x)*y*dp(x,y-1);
if(x&&y)f[x][y]+=1.0*x*y*dp(x-1,y-1);
f[x][y]+=1.0*n*n;
f[x][y]/=1.0*n*n-1.0*(n-x)*(n-y);
return f[x][y];
}
int main()
{
scanf("%d %d",&n,&m);h=l=n;
for(int i=1,x,y;i<=m;i++)
{
scanf("%d %d",&x,&y);
if(!line[x])line[x]^=1,h--;
if(!col[y])col[y]^=1,l--;
}
printf("%.10lf",dp(h,l));
}