avatar
fireworks99
keep hungry keep foolish

洛谷 P3389 高斯消元法(模板)

高斯消元法

设增广矩阵C = (A, b),其中A为方阵,高斯消元法是将系数矩阵A化为对角矩阵,然后用变化后的解向量中每一个元除以相应自变量的系数即可得到该自变量的估计值

代码须满足:方程个数 == 未知量的个数

Code

#include <cmath>
#include <cstdio>
#include <iostream>
#include <algorithm>
using namespace std;

int n;
double a[105][105];

int main()
{
    scanf("%d",&n);
    for(int i = 1; i <= n; ++i)
        for(int j = 1; j <= n + 1; ++j)
            scanf("%lf", &a[i][j]);
    for(int i = 1; i <= n; ++i)
    {
        ///据说将系数绝对值最大的方程转移到被减的这一行,可以减小误差
        ///1. 遍历行,选出该列最大系数
        int mmax = i;
        for(int j = i + 1; j <= n; ++j)
            if(fabs(a[j][i]) > fabs(a[mmax][i]))
                mmax = j;

        ///2. 交换两行
        for(int j = 1; j <= n + 1; ++j)
            swap(a[i][j],a[mmax][j]);

        ///3. 特例特判(最大值等于0则说明该列都为0,肯定无解)
        if(!a[i][i])
        {
            puts("No Solution");
            return 0;
        }

        ///4. 将第i列除第i行的其余元素化为0
        for(int j = 1; j <= n; ++j)
            if(j != i)
            {
                double temp = a[j][i] / a[i][i];
                for(int k = i ; k <= n + 1; ++k)
                    a[j][k] -= a[i][k] * temp;
            }
    }
///化增广矩阵,使系数变为对角矩阵
    for(int i = 1; i <= n; ++i)
        printf("%.2f\n", a[i][n+1] / a[i][i]);
    return 0;
}
Site by Baole Zhao | Powered by Hexo | theme PreciousJoy