1 #include <iostream> 2 #include <cstdio> 3 #include <cmath> 4 #include <algorithm> 5 using namespace std; 6 const double eps=1e-7; 7 const int maxn=1000; 8 int n;//n个变量 n个方程 9 double A[maxn][maxn]; 10 int Gauss() {//高斯消元 返回值 无解-- -1 11 //多解 -- 0 唯一解 -- 1(此时解保存在A[i][n+1]中) 12 int h,l,r;//h--行 l--列 13 for(h = 1,l = 1;h <= n && l <= n;++ h,++ l){//消系数矩阵(n*n) 14 r = h; 15 for(int i = h + 1;i <= n;++ i) if(fabs(A[i][l]) > fabs(A[r][l]) + eps) r=i;//找到当前列所有行中的最大值(做除法时减小误差) 16 if(r != h) for(int i = h;i <= n + 1;++ i) swap(A[r][i],A[h][i]); 17 if(fabs(A[h][l]) < eps) {--h;continue;}///当前列row行以下全为0(包括row行) 18 for(int i = h + 1;i <= n;++ i){ 19 if(fabs(A[i][l]) < eps) continue; 20 for(int j = n + 1;j >= l;-- j) A[i][j]-=A[i][l]/A[h][l]*A[h][j];//加减消元 21 } 22 } 23 for(int i = h;i <= n;++ i) if(A[i][l] > eps) return -1;//系数均为0但结果不为0 无解 24 if(h <= n) return 0;//消元后所得方程不足n个(否则h为n+1) 有多解 25 for(int i = n; i ;-- i){//有唯一解 此时为严格的上三角矩阵 代入消元 26 for(int j = i + 1;j <= n + 1;++ j) 27 A[i][n+1]-=A[i][j]*A[j][n+1]; 28 A[i][n+1]/=A[i][i]; 29 } 30 return 1; 31 } 32 int main() { 33 scanf("%d",&n); 34 for(int i = 1;i <= n;++ i) 35 for(int j = 1;j <= n + 1;++ j) 36 scanf("%lf",&A[i][j]); 37 int ans = Gauss(); 38 if(ans<=0) printf("%d",ans); 39 else 40 for(int i = 1;i <= n;++i){ 41 printf("x%d=", i); 42 if (fabs(A[i][n+1]) < eps) puts("0"); 43 else printf("%.2f\n", A[i][n+1]); 44 } 45 return 0; 46 }
洛谷P2455 [SDOI2006]线性方程组
猜你喜欢
转载自www.cnblogs.com/yu-xing/p/10344578.html
今日推荐
周排行