[HEOI2015][BZOJ4031] 小Z的房间 - Matrix-Tree定理

Description

你突然有了一个大房子,房子里面有一些房间。事实上,你的房子可以看做是一个包含n*m个格子的格状矩形,每个格子是一个房间或者是一个柱子。在一开始的时候,相邻的格子之间都有墙隔着。

你想要打通一些相邻房间的墙,使得所有房间能够互相到达。在此过程中,你不能把房子给打穿,或者打通柱子(以及柱子旁边的墙)。同时,你不希望在房子中有小偷的时候会很难抓,所以你希望任意两个房间之间都只有一条通路。现在,你希望统计一共有多少种可行的方案。

Input & Output

Input

第一行两个数分别表示n和m。

接下来n行,每行m个字符,每个字符都会是’.’或者’’,其中’.’代表房间,’’代表柱子。

Output

一行一个整数,表示合法的方案数 Mod 10^9

Sample

Input #1

2 2
..
..

Output #1

4

Input #2

2 2
*.
.*

Output #2

0

Solution

矩阵树定理,蒟蒻不打算在这里讲,各路神犇讲的不知道比我高到哪里去。然而……模数不是质数。从邢神那里get到一种神奇的高斯消元法。采用类似辗转相除法的方式来避免取不到逆元的尴尬。也就是并非一次消元完毕而是一部分一部分地消去,最后gcd中那个“b”也一定会变成0。具体实现见代码。
Code:

#include <iostream>
#include <cstdio>
#include <cmath>
#include <cstring>
#include <algorithm>

using std::min;
using std::max;
using std::cin;
using std::swap;
using std::fabs;
using std::isdigit;

typedef long long ll;

const ll p = 1000000000;
const int maxn = 105;

int n,m,id[15][15],ptr;
ll kirchhoff[maxn][maxn],dgr[maxn][maxn],gp[maxn][maxn];
char s[15][15];

void construct(int i,int j)
{
    if(s[i+1][j] == '.')
        gp[id[i][j]][id[i+1][j]] = 1,
        dgr[id[i+1][j]][id[i+1][j]]++;
    if(s[i-1][j] == '.')
        gp[id[i][j]][id[i-1][j]] = 1,
        dgr[id[i-1][j]][id[i-1][j]]++;      
    if(s[i][j+1] == '.')
        gp[id[i][j]][id[i][j+1]] = 1,
        dgr[id[i][j+1]][id[i][j+1]]++;
    if(s[i][j-1] == '.')
        gp[id[i][j]][id[i][j-1]] = 1,
        dgr[id[i][j-1]][id[i][j-1]]++;
}
void Gauss()
{
    for(int i = 1; i <= ptr; ++i)
        for(int j = 1; j <= ptr; ++j)
            kirchhoff[i][j] = (kirchhoff[i][j] + p) % p;
    ll res = 1 ,tag = 1;
    ptr--;
    for(int i = 1; i <= ptr; ++i)
    {
        for(int j = i + 1; j <= ptr; ++j)
        {
            ll a = kirchhoff[i][i], b = kirchhoff[j][i];
            while(b)
            {
                ll fac = a/b; a = a % b; swap(a,b);
                for(int k = i; k <= ptr; ++k)
                    kirchhoff[i][k] = (kirchhoff[i][k] - kirchhoff[j][k] * fac % p + p) % p, 
                    swap(kirchhoff[i][k], kirchhoff[j][k]);
                tag = -tag;
            }
        }
        if(kirchhoff[i][i] == 0)
        {
            puts("0");
            return;
        }
        res = res * kirchhoff[i][i] % p;
    }
    if(tag == -1) printf("%lld\n",(p-res)%p);
    else printf("%lld\n", res);
}

int main()
{
    scanf("%d%d",&n,&m);
    for(int i = 1; i <= n; ++i)
        for(int j = 1; j <= m; ++j)
            cin>>s[i][j];
    for(int i = 1; i <= n; ++i)
        for(int j = 1; j <= m; ++j)
            if(s[i][j] == '.')id[i][j] = ++ptr;
    for(int i = 1; i <= n; ++i)
        for(int j = 1; j <= m; ++j)
            if(s[i][j] == '.')construct(i,j);
    for(int i = 1; i <= ptr; ++i)
        for(int j = 1; j <= ptr; ++j)
            kirchhoff[i][j] = dgr[i][j] - gp[i][j];
    Gauss();
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/nishikino-curtis/p/9047798.html