• 矩阵求逆


    前言

    以前拖了好久,知道现在才知道怎么求矩阵求逆。果然是因为我是个大菜鸡。

    正言

    其实方法很简单,直接在原矩阵右边加上一个单位矩阵,然后高斯-约旦消元之后右边的那个矩阵就是逆矩阵了。

    正确性怎么说呢?应该很显然吧。。。

    ( ext {Code})

    #include <bits/stdc++.h>
    using namespace std;
    
    #define Int register int
    #define mod 1000000007
    #define MAXN 405
    
    template <typename T> inline void read (T &t){t = 0;char c = getchar();int f = 1;while (c < '0' || c > '9'){if (c == '-') f = -f;c = getchar();}while (c >= '0' && c <= '9'){t = (t << 3) + (t << 1) + c - '0';c = getchar();} t *= f;}
    template <typename T,typename ... Args> inline void read (T &t,Args&... args){read (t);read (args...);}
    template <typename T> inline void write (T x){if (x < 0){x = -x;putchar ('-');}if (x > 9) write (x / 10);putchar (x % 10 + '0');}
    
    int n,a[MAXN][MAXN << 1]; 
    
    int quick_pow (int a,int b){
    	int res = 1;for (;b;b >>= 1,a = 1ll * a * a % mod) if (b & 1) res = 1ll * res * a % mod;
    	return res;
    }
    
    signed main(){
    	read (n);
    	for (Int i = 1;i <= n;++ i){
    		for (Int j = 1;j <= n;++ j) read (a[i][j]);
    		a[i][n + i] = 1;
    	}
    	for (Int i = 1;i <= n;++ i){
    		int fir = 0;
    		for (Int j = i;j <= n;++ j) if (a[j][i]){fir = j;break;}
    		if (!fir) return puts ("No Solution"),0;
    		if (fir ^ i) swap (a[fir],a[i]);
    		int kk = quick_pow (a[i][i],mod - 2);
    		for (Int j = 1;j <= n;++ j){
    			if (j == i) continue;
    			int Inv = 1ll * a[j][i] * kk % mod;
    			for (Int k = i;k <= n << 1;++ k) a[j][k] = (a[j][k] + mod - 1ll * a[i][k] * Inv % mod) % mod;
    		}
    		for (Int j = 1;j <= n << 1;++ j) a[i][j] = 1ll * a[i][j] * kk % mod;
    	}
    	for (Int i = 1;i <= n;++ i){
    		for (Int j = 1;j <= n;++ j) write (a[i][j + n]),putchar (' ');
    		putchar ('
    ');
    	}
    	return 0;
    }
    
  • 相关阅读:
    Centos定时执行python脚本
    python 版websocket实现
    Linux Shell脚本实现根据进程名杀死进程
    /bin/bash^M: bad interpreter: 没有那个文件或目录
    python标准日志模块logging的使用方法
    对线程的理解
    Python处理JSON(转)
    div 模糊效果
    C#线程访问winform窗体控件
    iOS开发中添加PrefixHeader.pch要注意的问题
  • 原文地址:https://www.cnblogs.com/Dark-Romance/p/13273088.html
Copyright © 2020-2023  润新知