码迷,mamicode.com
首页 > 其他好文 > 详细

小Z的房间 (辗转相除gauss)

时间:2019-02-04 20:53:53      阅读:183      评论:0      收藏:0      [点我收藏+]

标签:main   getchar   bsp   char   string   amp   stack   span   辗转相除法   

gauss求解行列式时

如果模数不是质数,那么就要用到辗转相除法来消元

(为什么使用第 j 行减第 i 行啊qaq)

#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
#include<cmath>
#include<stack>
#include<queue>
using namespace std;
typedef long long ll;

const int maxn = 1000;
const int P = 1e9;

int n,m,cnt,ans;
int a[maxn][maxn],b[maxn][maxn],d[maxn][maxn],c[maxn][maxn];
char ch[maxn][maxn];

void add(int u,int v){ d[u][u]++,c[u][v]=1; }

void gauss(){
    ans=1;
    int f=1;
    for(int i=2;i<=cnt;i++){
        for(int j=i+1;j<=cnt;j++){
            int x=a[i][i],y=a[j][i];
            while(y){
                int t=x/y; x%=y; swap(x,y);
                for(int k=i;k<=cnt;k++){
                    a[i][k]=(a[i][k]-1ll*t*a[j][k]%P+P)%P;
                    swap(a[i][k],a[j][k]);
                }
                f=-f;
            }
        }
        if(!a[i][i]){ ans=0; return; }
        ans=1ll*ans*a[i][i]%P;
    }
    if(f==-1) ans=(P-ans)%P;
}

ll read(){ ll s=0,f=1; char ch=getchar(); while(ch<0 || ch>9){ if(ch==-) f=-1; ch=getchar(); } while(ch>=0 && ch<=9){ s=s*10+ch-0; ch=getchar(); } return s*f; }

int main(){
    n=read(),m=read();
    for(int i=1;i<=n;i++){ scanf("%s",ch[i]); }
    for(int i=1;i<=n;i++) for(int j=0;j<m;j++) if(ch[i][j]==.) b[i][j+1]=++cnt;
    for(int i=1;i<=n;i++){
        for(int j=1;j<=m;j++){
            if(b[i][j]){
                if(i-1>0 && b[i-1][j]) add(b[i][j],b[i-1][j]);
                if(j-1>0 && b[i][j-1]) add(b[i][j],b[i][j-1]);
                if(i+1<=n && b[i+1][j]) add(b[i][j],b[i+1][j]);
                if(j+1<=m && b[i][j+1]) add(b[i][j],b[i][j+1]);
            }
        }
    }
    
    for(int i=1;i<=cnt;i++){
        for(int j=1;j<=cnt;j++){
            if(i==j) a[i][j]=d[i][j];
            else a[i][j]=(a[i][j]-c[i][j]+P)%P;
        }
    }
    
    gauss();
    printf("%d\n",ans);
    
    return 0;
}

 

小Z的房间 (辗转相除gauss)

标签:main   getchar   bsp   char   string   amp   stack   span   辗转相除法   

原文地址:https://www.cnblogs.com/tuchen/p/10352092.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!