• 矩阵求逆


    前言

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

    正言

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

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

    ( 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;
    }
    
  • 相关阅读:
    POJ 3977 折半枚举
    [CQOI2007]余数求和 (分块+数学
    NOI P1896 互不侵犯 状压DP
    HDU 5446 Unknown Treasure (卢卡斯+CRT
    宁夏邀请赛F FLOYD
    P1414 又是毕业季II (数学?
    P2051 [AHOI2009]中国象棋 DP
    POJ 2449:Remmarguts' Date(A* + SPFA)
    HDU 6215:Brute Force Sorting(链表+队列)
    HDU 6207:Apple(Java高精度)
  • 原文地址:https://www.cnblogs.com/Dark-Romance/p/13273088.html
Copyright © 2020-2023  润新知