90pts求助,高斯消元

P2455 [SDOI2006] 线性方程组

GG_and_go_to_died @ 2024-02-12 19:39:59


#include <cmath>
#include <cstdio>
#include <iostream>
#include <algorithm>
#define init signed
#define int double
using namespace std;

init n;
int guass[105][105];

void cheak()
{
    for (init i = 1;i <= n; ++ i)
    {
        if (guass[i][i] == 0)
        {
            if (guass[i][n + 1] == 0)
            {
                cout << 0 << endl;
                exit(0);
            }
            else
            {
                cout << -1 << endl;
                exit(0);
            }
        }
    }
}

init main()
{
    ios::sync_with_stdio(false);
    cin.tie(0) , cout.tie(0);
    cin >> n;
    for (init i = 1;i <= n; ++ i)
    {
        for (init j = 1;j <= n + 1; ++ j)
        {
            cin >> guass[i][j];
        }
    }
    //消元
    for (init i = 1;i <= n; ++ i)
    {
        init maxn_p;
        int maxn = 0;
        for (init j = i;j <= n; ++ j)
        {
            if (fabs(guass[j][i]) >= maxn)
            {
                maxn = fabs(guass[j][i]);
                maxn_p = j;
            }
        }
        for (init j = 1;j <= n + 1; ++ j)
        {
            swap(guass[maxn_p][j] , guass[i][j]);
        }
        if(guass[i][i] == 0)
        {
            continue;
        }
        for (init j = i + 1;j <= n + 1; ++ j)
        {
            guass[i][j] /= guass[i][i];
        }
        for (init j = i + 1;j <= n; ++ j)
        {
            int l = guass[j][i];
            for (init k = 1;k <= n + 1; ++ k)
            {
                guass[j][k] -= l * guass[i][k] ;
            }  
        }

    }
    //回带
    for (init i = n - 1;i >= 1; -- i)
    {
        for (init j = i + 1;j <= n; ++ j)
        {
            guass[i][n + 1] -= guass[i][j] * guass[j][n + 1];
        }
    }
    cheak();
    for (init i = 1;i <= n; ++ i)
    {
        printf("x%d=%.2lf\n", i , guass[i][n + 1]);
    }
    return 0;
}

by Terrible @ 2024-02-12 19:56:01

@GG_and_go_to_died

你的 cheak 函数写得有点问题,不仅仅是内容有问题 (不是 check 吗?)

改成下面这样可过:

void cheak()
{
    bool havesolution=true,probablyinf=false;
    for (init i = 1;i <= n; ++ i)
    {
        if (guass[i][i] == 0)
        {
            if (guass[i][n + 1] == 0)
            {
                probablyinf=true;
            }
            else
            {
                havesolution=false;
            }
        }
    }
    if(!havesolution)cout<<-1,exit(0);
    else if(probablyinf)cout<<0,exit(0);
}

如果判断有 0x=0 这样的情况先不要判断无穷个解,因为下面还有可能有 0x=1 的情况,这种就是你提前输出了 0

另外,似乎写正规程序的时候不应该在使用了 C++ 类对象之后 exit(0)?这样似乎、可能会产生一些奇怪的问题。不过似乎评测机里面这么写问题不大 出问题又不是你的电脑会炸掉


by GG_and_go_to_died @ 2024-02-12 19:57:53

@Terrible 谢谢


by GG_and_go_to_died @ 2024-02-12 20:03:55

已关


|