天天看点

AcWing 883. 高斯消元解线性方程组(高斯消元)

这完全就是线性代数的矩阵解方程

但是代码写起来还是有点麻烦的。

题目

浮点数比较还是用一个误差计算合适,Java有时候也不能完美的处理浮点数运算。

类似这样double xxx = 1e-6;

AcWing 883. 高斯消元解线性方程组(高斯消元)
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;

public class Main {
    static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    static PrintWriter pw = new PrintWriter(System.out);
    static int N = 110;
    static int n;
    static double a[][] = new double[N][N];
    static double dieta = 1e-6;	//

    public static void main(String[] args) throws IOException {
        String[] s = br.readLine().split(" ");
        n = Integer.parseInt(s[0]);
        for (int i = 0; i < n; i++) {
            s = br.readLine().split(" ");
            //System.debug.println(s[0] + " " +  s[1] + " " + s[2] + " " + s[3]);
            for (int j = 0; j < n + 1; j++)
                a[i][j] = Double.parseDouble(s[j]);
        }
        //debug();
        int res = guass();
        if (res == 1) pw.println("Infinite group solutions");
        else if (res == 0)
            for (int i = 0; i < n; i++)
                pw.println(String.format("%.2f", a[i][n]));
        else pw.println("No solution");
        pw.flush();
        br.close();
    }

    public static int guass() {
        int r, c;
        for (c = 0, r = 0; c < n; c++) {
            int t = r;
            for (int i = r; i < n; i++)
                if (Math.abs(a[i][c]) > Math.abs(a[t][c]))
                    t = i;      //定位最大绝对值(非前0)

            if (Math.abs(a[t][c]) == 0) continue;   //忽略前0

            for (int i = c; i <= n; i++) { //换到第一排
                double temp = a[t][i];
                a[t][i] = a[r][i];
                a[r][i] = temp;
            }
            //debug();
            for (int i = n; i >= c; i--) a[r][i] /= a[r][c]; // 规整一排 前1
            //debug();
            for (int i = r + 1; i < n; i++)
                if (Math.abs(a[i][c]) > dieta)
                    for (int j = n; j >= c; j--)
                        a[i][j] -= a[r][j] * a[i][c];
            //debug();
            r++;
        }
        if (r < n) {
            for (int i = r; i < n; i++)
                if (a[i][n] != 0)
                    return -1;   //无解
            return 1;      //无穷解
        }

        for (int i = n - 1; i >= 0; i--)
            for (int j = i + 1; j < n; j++)
                a[i][n] -= a[i][j] * a[j][n];

        return 0;
    }

    public static void debug() {
        for (int i = 0; i < n; i++) {
            for (int j = 0; j <= n; j++)
                pw.print("    " + a[i][j] + "    ");
            pw.println();
        }
        pw.println();
    }

}
           

继续阅读