# 【BZOJ-4031】小z的房间 Matrix-Tree定理 + 高斯消元解行列式

## 4031: [HEOI2015]小Z的房间

Time Limit: 10 Sec  Memory Limit: 256 MB
Submit: 937  Solved: 456
[Submit][Status][Discuss]

## Output

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

3 3
...
...
.*.

15

## Code

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
using namespace std;
#define LL long long
#define P 1000000000
char mp[50][50];
int N,M,dx[4]={-1,0,1,0},dy[4]={0,1,0,-1},A[100][100],D[100][100],id[10][10],ID;
LL G[100][100];

inline bool check(int x,int y) {return x>=1&&x<=N&&y>=1&&y<=M&&mp[x][y]!='*';}
inline void InsertEdge(int u,int v) {D[v][v]++; A[u][v]=1;}
inline LL Gauss()
{
int f=1; LL ans=1;

ID--;

for (int i=1; i<=ID; i++)
for (int j=1; j<=ID; j++)
G[i][j]=(G[i][j]+P)%P;

//	for (int i=1; i<=ID; i++,puts(""))
//		for (int j=1; j<=ID; j++) printf("%d  ",G[i][j]);

for (int i=1; i<=ID; i++) {
for (int j=i+1; j<=ID; j++) {
LL x=G[i][i],y=G[j][i];
while (y) {
LL t=x/y; x%=y; swap(x,y);
for (int k=i; k<=ID; k++)
G[i][k]=(G[i][k]-t*G[j][k]%P+P)%P;
for (int k=i; k<=ID; k++)
swap(G[i][k],G[j][k]);
f=-f;
}
}

if (!G[i][i]) return 0;
ans=ans*G[i][i]%P;
}

if (f==-1) return (P-ans)%P;
return ans;
}

int main()
{
//	freopen("room.in","r",stdin);
//	freopen("room.out","w",stdout);

scanf("%d%d",&N,&M);
for (int i=1; i<=N; i++) scanf("%s",mp[i]+1);

for (int i=1; i<=N; i++)
for (int j=1; j<=M; j++) if (mp[i][j]!='*') id[i][j]=++ID;

for (int i=1; i<=N; i++)
for (int j=1; j<=M; j++)
if (mp[i][j]!='*')
for (int d=0; d<4; d++) {
int tx=i+dx[d],ty=j+dy[d];
if (check(tx,ty)) InsertEdge(id[i][j],id[tx][ty]);
}

for (int i=1; i<=ID; i++)
for (int j=1; j<=ID; j++) G[i][j]=D[i][j]-A[i][j];

printf("%lld\n",Gauss());

return 0;
}


——It's a lonely path. Don't make it any lonelier than it has to be.
posted @ 2017-02-27 19:50  DaD3zZ  阅读(489)  评论(0编辑  收藏  举报