luogu P2455 [SDOI2006]线性方程组 题解
Posted Misaka_Azusa
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了luogu P2455 [SDOI2006]线性方程组 题解相关的知识,希望对你有一定的参考价值。
题目链接:https://www.luogu.org/problemnew/show/P2455
嗯...在消元过程中不要直接拿矩阵元素自己消,会把自己消成0.
1 #include <algorithm> 2 #include <cstdio> 3 #include <cmath> 4 #include <iostream> 5 using namespace std; 6 const int maxn = 200; 7 const double eps = 1e-7; 8 double A[maxn][maxn], ans[maxn]; 9 int n; 10 int main() 11 { 12 scanf("%d",&n); 13 for(int i = 1; i <= n; i++) 14 for(int j = 1; j <= n+1; j++) 15 scanf("%lf", &A[i][j]); 16 for(int i = 1; i <= n; i++) 17 { 18 int p = i; 19 for(int j = i + 1; j <= n; j++) 20 if(fabs(A[j][i]) > fabs(A[p][i])) p = j; 21 for(int j = 1; j <= n + 1; j++) swap(A[p][j],A[i][j]); 22 23 if(fabs(A[i][i]) < eps) continue; 24 double div = A[i][i]; 25 for(int j = 1; j <= n + 1; j++) A[i][j]/=div; 26 for(int j = 1; j <= n; j++) 27 { 28 if(i != j) 29 { 30 double div = A[j][i]; 31 for(int k = 1; k <= n + 1; k++) A[j][k] -= A[i][k]*div; 32 } 33 } 34 } 35 int NoSolution = 0, ManySolution = 0; 36 for(int i = 1; i <= n; i++) 37 { 38 int Nonum = 0, Manynum = 0; 39 for(int j = 1; j <= n + 1 && fabs(A[i][j]) < eps; j++) 40 Nonum++,Manynum++; 41 if(Manynum > n) ManySolution = 1; 42 if(Nonum == n) NoSolution = 1; 43 } 44 if(NoSolution) {printf("-1");return 0;} 45 if(ManySolution) {printf("0");return 0;} 46 for(int i = n; i >= 1; i--) 47 { 48 ans[i] = A[i][n+1]; 49 for(int j = i - 1; j >= 1; j--) 50 { 51 A[j][n+1] -= ans[i] * A[j][i]; 52 A[j][i] = 0; 53 } 54 } 55 for(int i = 1; i <= n; i++) 56 printf("x%d=%.2lf\n",i,ans[i] + eps); 57 return 0; 58 }
以上是关于luogu P2455 [SDOI2006]线性方程组 题解的主要内容,如果未能解决你的问题,请参考以下文章