【模板】高斯消元法

洛谷1583

 1 #include<cstdio>
 2 #include<algorithm>
 3 using namespace std;
 4 const int maxn=1000;
 5 int n,x;
 6 double a[maxn][maxn];
 7 inline void read(int &k){
 8     k=0; int f=1; char c=getchar();
 9     while(c<'0'||c>'9')c=='-'&&(f=-1),c=getchar();
10     while('0'<=c&&c<='9')k=k*10+c-'0',c=getchar();
11     k*=f;
12 }
13 void swap_a(int x,int y){for (int i=1;i<=n+1;i++) swap(a[x][i],a[y][i]);}
14 bool Gauss(){
15     int now=1;
16     while(now<=n){
17         if (a[now][now]==0){
18             for (int i=now+1;i<=n;i++) if(a[i][now]!=0) {swap_a(i,now); break;}
19             if (a[now][now]==0) return puts("No Solution"),0;
20         } 
21         double tmp=a[now][now];
22         for (int i=1;i<=n+1;i++) a[now][i]=a[now][i]/tmp;  
23         for (int i=1;i<=n;i++){                        
24             if (i==now) continue; double tmp=a[i][now];
25             for (int j=1;j<=n+1;j++) a[i][j]-=a[now][j]*tmp;
26         }
27         now++;
28     }
29     return 1;
30 }
31 int main(){
32     read(n);
33     for (int i=1;i<=n;i++)
34         for (int j=1;j<=n+1;j++) read(x),a[i][j]=x;
35     if (Gauss()) for (int i=1;i<=n;i++) printf("%.2f\n",a[i][n+1]); printf("\n");
36     return 0;
37 } 
View Code
posted @ 2017-12-04 20:50  Driver_Lao  阅读(185)  评论(0编辑  收藏  举报