Description
你突然有了一个大房子,房子里面有一些房间。事实上,你的房子可以看做是一个包含
n×m
n
×
m
个格子的格状矩形,每个格子是一个房间或者是一个柱子。在一开始的时候,相邻的格子之间都有墙隔着。
你想要打通一些相邻房间的墙,使得所有房间能够互相到达。在此过程中,你不能把房子给打穿,或者打通柱子(以及柱子旁边的墙)。同时,你不希望在房子中有小偷的时候会很难抓,所以你希望任意两个房间之间都只有一条通路。现在,你希望统计一共有多少种可行的方案。
Input
第一行两个数分别表示
n
n
和 。
接下来
n
n
行,每行 个字符,每个字符都会是
.
.
或者 ,其中
.
.
代表房间, 代表柱子。
Output
一行一个整数,表示合法的方案数 mod109 mod 10 9 。
Sample Input
3 3
…
…
.*.
Sample Output
15
HINT
对于前 100% 的数据, n,m≤9 n , m ≤ 9
Solution
考虑把每个房间看作一个点,相邻的房间之间连边。
那么题目显然是一个生成树计数问题。
于是这就是一道Matrix-Tree矩阵树定理裸题。
矩阵树定理及其证明:
https://blog.csdn.net/werkeytom_ftd/article/details/54914530
高斯消元实现求行列式即可得到答案。
同时注意此题的取模。假如要利用第
i
i
行对第 行进行消元,使得
(j,i)
(
j
,
i
)
变为
0
0
,
那么应该对 和
(j,i)
(
j
,
i
)
位置上的值进行辗转相除,具体见代码。
而在此过程中,有两行的交换操作,行列式会跟着取反,因此要用一个变量记录行列式是否被取反。
Code
#include <cmath>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#define For(i, a, b) for (i = a; i <= b; i++)
using namespace std;
const int D = 11, N = 90, PYZ = 1e9;
int r, c, n, id[D][D], dx[] = {0, 0, -1, 1}, dy[] = {1, -1, 0, 0},
mat[N][N];
char s[D][D]; bool con[N][N];
int solve() {
int i, j, k; bool tr = 0; For (i, 1, n) For (j, i + 1, n) {
int a = mat[i][i], b = mat[j][i]; while (b) {
int tmp = a / b; a %= b; swap(a, b);
For (k, i, n) mat[i][k] = (mat[i][k] - 1ll * tmp * mat[j][k]
% PYZ + PYZ) % PYZ;
For (k, i, n) swap(mat[i][k], mat[j][k]); tr ^= 1;
}
}
int ans = 1; For (i, 1, n) ans = 1ll * ans * mat[i][i] % PYZ;
return tr ? (PYZ - ans) % PYZ : ans;
}
int main() {
int i, j, k; cin >> r >> c; For (i, 1, r) scanf("%s", s[i] + 1);
For (i, 1, r) For (j, 1, c) if (s[i][j] == '.') id[i][j] = ++n;
For (i, 1, r) For (j, 1, c) if (id[i][j]) For (k, 0, 3) {
int tx = i + dx[k], ty = j + dy[k]; if (!id[tx][ty]) continue;
con[id[i][j]][id[tx][ty]] = 1;
}
For (i, 1, n) For (j, 1, n) mat[i][i] += con[i][j];
For (i, 1, n) For (j, 1, n) if (con[i][j]) mat[i][j] = PYZ - 1;
n--; cout << solve() << endl; return 0;
}