其他分享
首页 > 其他分享> > 矩阵求逆

矩阵求逆

作者:互联网

LuoguP4783

思路:

求A的逆矩阵,把A和单位矩阵I放在一个矩阵里

对A进行加减消元使A化成单位矩阵

此时原来单位矩阵转化成逆矩阵

原理大概就是 A(逆) * [A I] = [I A(逆)]

Code:

 1 #include <bits/stdc++.h>
 2 #define ll long long
 3 using namespace std;
 4 const double eps = 1E-8;
 5 const int p = 1e9 + 7;
 6 const int N = 405;
 7 int n, m;
 8 ll a[N][N << 1];
 9 ll pw(ll x, ll y) {
10     ll re = 1;
11     for (; y; y >>= 1) {
12         if (y & 1) {
13             re = re * x % p;
14         }
15         x = x * x % p;
16     }
17     return re;
18 }
19 void gauss() {//高斯消元 
20     for (int i = 1; i <= n; i++) {
21         int pre = i;
22         for (int j = i + 1; j <= n; j++) {
23             if (fabs(a[j][i] - a[pre][i]) >= eps) {
24                 pre = j;
25             }
26         }
27         for (int k = 1; k <= m; k++) {//交换着两行,记得把右侧新添矩阵也交换 
28             swap(a[i][k], a[pre][k]);
29         }
30         if (fabs(a[i][i]) <= eps) {
31             printf("No Solution\n");
32             exit(0);
33         }
34         ll inv = pw(a[i][i], p - 2);//求逆元 
35         for (int k = i; k <= m; k++) {
36             a[i][k] = a[i][k] * inv % p;
37         }
38         for (int j = 1; j <= n; j++) {
39             if (i != j) {
40                 for (int k = i + 1; k <= m; k++) {//在当前矩阵进行变换时,对所求矩阵也进行同样的变换 
41                     a[j][k] = (a[j][k] - a[j][i] * a[i][k] % p + p) % p;
42                 }
43                 a[j][i] = 0;
44             }
45         }
46     }
47 }
48 int main () {
49     scanf("%d", &n);
50     for (int i = 1; i <= n; i++) {
51         for (int j = 1; j <= n; j++) {
52             scanf("%lld", &a[i][j]);
53         }
54         a[i][n + i] = 1;//另一半初始化为元矩阵 
55     }
56     m = n << 1;
57     gauss();
58     for (int i = 1; i <= n; i++) {
59         for (int j = n + 1; j <= m; j++) {
60             printf("%lld%c", a[i][j], j == m ? '\n' : ' ');
61         }
62     }
63     return 0;
64 }
View Code

 

标签:求逆,const,int,矩阵,ll,单位矩阵,re
来源: https://www.cnblogs.com/Sundial/p/11830555.html