高斯消元模板

 

  推荐一个讲得不错的博客:http://www.cnblogs.com/ECJTUACM-873284962/p/6880199.html  

  洛谷模板题:https://www.luogu.org/problemnew/show/P3389

 

模板题代码:

 1 #include<iostream>
 2 #include<cstdio>
 3 #include<cstring>
 4 #include<algorithm>
 5 #include<cmath>
 6 #define LL long long
 7 #define RI register int
 8 #define eps 1e-7 
 9 using namespace std;
10 const int INF = 0x7ffffff ;
11 const int N = 100 + 10 ;
12 
13 inline int read() {  // 快读 
14     int k = 0 , f = 1 ; char c = getchar() ;
15     for( ; !isdigit(c) ; c = getchar())
16       if(c == '-') f = -1 ;
17     for( ; isdigit(c) ; c = getchar())
18       k = k*10 + c-'0' ;
19     return k*f ;
20 }
21 int n ; double hh[N][N] ;
22 
23 inline bool guass() {
24     for(int i=0;i<n;i++) {  // 转换成上三角矩阵过程 
25         int r = i ; double maxx = hh[i][i] ;
26         for(int j=i+1;j<n;j++) {
27             if(hh[j][i] > hh[r][i]) r = j ;
28         }
29         if(fabs(hh[r][i]) < eps) return 0 ;  // 因为有精度误差,所以除了x1有无数解时是严格等于0的,其他时候都只是接近0而已 
30         if(r != i) for(int j=i;j<=n;j++) swap(hh[i][j],hh[r][j]) ;
31         for(int j=i+1;j<n;j++) {
32             double f = hh[j][i]/hh[i][i] ;
33             for(int k=i;k<=n;k++) {
34                 hh[j][k] -= hh[i][k]*f ;
35             }
36         }
37     }
38     for(int i=n-1;i>=0;i--) {  // 回带过程 
39         for(int j=i+1;j<n;j++) hh[i][n] -= hh[i][j]*hh[j][n] ;
40         hh[i][n] /= hh[i][i] ;
41     }
42     return 1 ;
43 }
44 
45 int main() {
46     n = read() ;
47     for(int i=0;i<n;i++) {
48         for(int j=0;j<=n;j++)
49           hh[i][j] = read() ;
50     }
51     if(!guass()) {
52         printf("No Solution") ;
53     } else {
54         for(int i=0;i<n;i++) printf("%.2lf
",hh[i][n]) ;
55     }
56     return 0 ;
57 }

  大家看着代码照着样例手动模拟一下过程就能理解了。 (实践出真知啊qwq)

原文地址:https://www.cnblogs.com/zub23333/p/8610803.html