Inverse matrix [template]

topic

P4783

Seeking a $ N \ inverse matrix of times N $ matrix. The answer modulo $ 10 $ ^ 9 + 7. If not reversible, output "No Solution".

analysis

Knowledge of linear algebra, the inverse matrix A, the

Just to add to the right of a matrix A, a primary transformation, when A becomes an identity matrix, the right is the inverse matrix A.

Simple proof: $ AE \ rightarrow E {A} '$

Code

// from https://blog.csdn.net/qq_43653202/article/details/99976316

#include<iostream>
#include<cstdio>
#include<cmath>
#define re register
#define il inline
#define ll long long
using namespace std;

il ll read(){
    ll s=0,f=0;char c=getchar();
    while(c<'0'||c>'9') f=(c=='-'),c=getchar();
    while(c>='0'&&c<='9') s=(s<<3)+(s<<1)+(c^'0'),c=getchar();
    return f?-s:s;
}

const int N=405,mod=1e9+7;
int n;
ll a[N][N<<1];
il ll qpow(ll x,ll k){
    ll ans=1;
    while(k){
        if(k&1) ans=ans*x%mod;
        x=x*x%mod;
        k>>=1;
    }
    return ans%mod;
}

il void Gauss_j(){
    for(re int i=1,r;i<=n;++i){
        r=i;
        for(re int j=i+1;j<=n;++j)
            if(a[j][i]>a[r][i]) r=j;
        if(r!=i) swap(a[i],a[r]);
        if(!a[i][i]){puts("No Solution");return;}

        int kk=qpow(a[i][i],mod-2); //求逆元
        for(Re int K = . 1 ; K <= n-; ++ K) {
             IF (K == I) Continue ;
             int P A = [K] [I] * KK% MOD;
             for (Re int J = I; J <= (n-<< . 1 ); ++ J) 
                A [K] [J] = ((A [K] [J] -p * A [I] [J]) + MOD% MOD)% MOD; 
        } 

        for (Re int J = . 1 ; J <= (n-<< . 1 ); J ++) A [I] [J] = (A [I] [J] *% KK MOD);
         // update the current row if seek time again on the final inverse element, as a direct placed here 
    } 

    for (Re int I = . 1;i<=n;++i){
        for(re int j=n+1;j<(n<<1);++j) printf("%lld ",a[i][j]);
        printf("%lld\n",a[i][n<<1]);
    }
}
int main(){
    n=read();
    for(re int i=1;i<=n;++i)
        for(re int j=1;j<=n;++j)
            a[i][j]=read(),a[i][i+n]=1;

    Gauss_j();
    return 0;
}

 

Guess you like

Origin www.cnblogs.com/lfri/p/11618589.html