首页 > 其他 > 详细

高斯消元【模板】

时间:2019-05-22 14:09:04      阅读:103      评论:0      收藏:0      [点我收藏+]

传送门:

#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
using namespace std;
#define ll long long
#define re register
const double eps=1e-8;
inline void read(int &a)
{
    a=0;
    int d=1;
    char ch;
    while(ch=getchar(),ch>9||ch<0)
        if(ch==-)
            d=-1;
    a=ch^48;
    while(ch=getchar(),ch>=0&&ch<=9)
        a=(a<<3)+(a<<1)+(ch^48);
    a*=d;
}
double a[105][105],ans[105];
int main()
{
    int n;
    read(n);
    for(re int i=1;i<=n;i++)
        for(re int j=1;j<=n+1;j++)
            scanf("%lf",&a[i][j]);
    for(re int i=1;i<=n;i++)
    {
        int r=i;
        for(re int j=i+1;j<=n;j++)
            if(fabs(a[r][i])<fabs(a[j][i]))
                r=j;
        if(fabs(a[r][i])<eps)
        {
            printf("No Solution\n");
            return 0;
        }
        if(r!=i)
            swap(a[r],a[i]);
        double div=a[i][i];
        for(re int j=i;j<=n+1;j++)
            a[i][j]/=div;
        for(re int j=i+1;j<=n;j++)
        {
            div=a[j][i];
            for(re int k=i;k<=n+1;k++)
                a[j][k]-=a[i][k]*div;
        }
    }
    ans[n]=a[n][n+1];
    for(re int i=n-1;i>=1;i--)
    {
        ans[i]=a[i][n+1];
        for(re int j=i+1;j<=n;j++)
            ans[i]-=a[i][j]*ans[j];
    }
    for(re int i=1;i<=n;i++)
        printf("%.2lf\n",ans[i]);
    return 0;
}

 

高斯消元【模板】

原文:https://www.cnblogs.com/acm1ruoji/p/10905544.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!