1. 程式人生 > >[BZOJ 1013] [JSOI 2008] 球形空間產生器sphere

[BZOJ 1013] [JSOI 2008] 球形空間產生器sphere

Description

題面

Solution

以三維空間為例,設圓心為 \((x_1,x_2,x_3)\),有

\[ \begin{array}\\ (a_1-x_1)^2+(a_2-x_2)^2+(a_3-x_3)^2 &=& (b_1-x_1)^2+(b_2-x_2)^2+(b_3-x_3)^2\\ a_1^2-2a_1x_1+x_1^2+a_2^2-2a_2x_2+x_2^2+a_3^2-2a_3x_3+x_3^2 &=& b_1^2-2b_1x_1+x_1^2+b_2^2-2b_2x_2+x_2^2+b_3^2-2b_3x_3+x_3^2\\ a_1^2-2a_1x_1+a_2^2-2a_2x_2+a_3^2-2a_3x_3 &=& b_1^2-2b_1x_1+b_2^2-2b_2x_2+b_3^2-2b_3x_3\\ 2(b_1-a_1)x_1+2(b_2-a_2)x_2+2(b_3-a_3)x_3 &=& (b_1^2-a_1^2)+(b_2^2-a_2^2)+(b_3^2-a_3^2) \end{array} \]

高斯消元模板。

Code

#include <cstdio>
#include <algorithm>

int n; double a[15][15], b[15];

double fabs(double x) {
    return x < 0 ? -x : x;
}

void gauss() {
    for (int i = 1; i <= n; ++i) {
        int k = i;
        for (int j = i + 1; j <= n; ++j)
            if (fabs(a[j][i]) > fabs(a[k][i])) k = j;
        std::swap(a[i], a[k]);
        for (int j = n + 1; j >= i; --j) a[i][j] /= a[i][i];
        for (int j = 1; j <= n; ++j) {
            if (j != i && a[j][i]) for (int k = n + 1; k >= i; --k)
                a[j][k] -= a[j][i] * a[i][k];
        }
    }
}

int main() {
    scanf("%d", &n);
    for (int i = 1; i <= n; ++i) scanf("%lf", &b[i]);
    for (int i = 1; i <= n; ++i)
        for (int j = 1; j <= n; ++j) {
            scanf("%lf", &b[n+1]);
            a[i][j] = 2 * (b[n+1] - b[j]);
            a[i][n+1] += b[n+1] * b[n+1] - b[j] * b[j];
        }
    gauss();
    for (int i = 1; i <= n; ++i) printf("%.3lf ", a[i][n+1]);
    return 0;
}